Interview Questions
Memory Allocation · Study material
C Memory Allocation Interview Questions and Answers
1. What is the difference between stack and heap memory?
The stack holds local variables and is freed automatically when a function returns; it is fast but small. The heap holds memory from malloc() and friends, lives until free(), and is much larger.
2. What does malloc() return when it fails?
A null pointer. Always check before using the result.
3. What is the difference between malloc() and calloc()?
calloc(n, size) zero-fills the memory and guards against overflow in n × size; malloc(bytes) does neither.
4. Why is p = realloc(p, n) a bug?
If realloc() fails it returns NULL but does not free the old block. Assigning NULL to p loses the only pointer to it – a leak. Use a temporary.
5. What is a memory leak?
Allocated memory that is never freed and can no longer be reached, typically because the pointer was overwritten or went out of scope.
6. What is a dangling pointer?
A pointer to memory that has been freed (or to a local variable that no longer exists). Using it is undefined behaviour.
7. Is free(NULL) safe?
Yes, it does nothing. That is why setting a pointer to NULL after freeing it prevents double-free bugs.
8. What is the difference between memcpy() and memmove()?
memmove() works correctly when source and destination overlap; memcpy() has undefined behaviour in that case but can be faster.
9. Should you cast the return value of malloc() in C?
No. void * converts implicitly; the cast is redundant and can hide a missing header in older C. C++ requires it.
10. What does malloc(0) return?
It is implementation-defined: either NULL or a unique pointer that must not be dereferenced but can be passed to free().
11. What changed for memory allocation in C23?
realloc(p, 0) became undefined behaviour, free_sized() and free_aligned_sized() were added, and nullptr gives a typed null pointer constant.
12. How do you find memory bugs in practice?
Compile with AddressSanitizer (-fsanitize=address) or run under Valgrind; both report leaks, overflows, use-after-free and double frees with the exact source line.