- The four dynamic memory functions: malloc, calloc, realloc, free
- The return type void* and why NULL checks matter
- Difference between malloc and calloc (zeroing)
- Resizing memory blocks safely with realloc
- Common bugs: memory leaks, double-free, dangling pointers
- Memory fragmentation and how to avoid it
- Why
freedoesn't set the pointer to NULL - Best practices for defensive dynamic memory code
This page has 40 multiple choice questions on dynamic memory allocation in C. You'll find questions on malloc, calloc, realloc, and free — what each does, what it returns, and when to use it. You'll also see questions on memory leaks, dangling pointers, double-free bugs, fragmentation, and error handling. Each question comes with the correct answer and a short explanation in plain English, so you understand the "why" and not just the "what". Dynamic memory is heavily tested in interviews and real-world debugging, so mastering these functions pays off in both.
Dynamic Memory Basics
Q1. Which library header must be included to use dynamic memory functions in C?
Answer: a) <stdlib.h>
malloc, calloc, realloc, and free are all declared in stdlib.h. Without this header, the compiler doesn't know their signatures and may reject your code (or, in old C, silently assume they return int, which truncates pointers — a nasty bug). Include stdlib.h at the top of any file using these functions.
Q2. Which function is used to allocate memory dynamically in C?
Answer: a) malloc()
malloc (memory allocation) is the primary dynamic allocation function. calloc and realloc are variants, and free releases memory. When asked "the function to allocate", malloc is the canonical answer — it allocates a block of n bytes and returns a void* to it (or NULL). Use it when you need memory whose size is decided at runtime.
Q3. What is the return type of malloc() in C?
Answer: a) void*
malloc returns void* — a generic pointer to untyped memory. In C, this converts implicitly to any pointer type, so you can write int *p = malloc(...) without a cast. The cast (int *)malloc(...) is optional in C but required in C++. In C, casting is actually discouraged by many style guides because it can hide a missing stdlib.h.
Q4. Where is dynamically allocated memory stored?
Answer: c) On the heap
Dynamic memory lives in the heap — a region of memory managed by malloc and free, separate from the stack. Unlike the stack, the heap grows on demand and persists until you explicitly free it. That's why dynamic memory has program-wide lifetime until freed. Stack is for auto variables, data segment for statics and globals.
Q5. What is the correct syntax to allocate memory for one int in C?
Answer: a) int *p = malloc(sizeof(int));
malloc takes a byte count, so you must use sizeof(type) to compute the correct size. Option b) passes a type name (not a value), c) allocates a pointer-sized block (wrong for one int on most systems), and d) uses a non-existent "size" function. The idiom malloc(sizeof(T)) or malloc(n * sizeof(T)) appears in nearly every C program that allocates.
Q6. How is memory deallocated in C after dynamically allocating it?
Answer: a) free()
free(ptr) releases a block obtained from malloc, calloc, or realloc. It returns the memory to the heap manager for future allocations. delete is a C++ operator — not valid in C. dealloc and release don't exist in C. Every dynamic allocation must be matched by exactly one free.
Q7. Which memory allocation function in C allows resizing of an existing block?
Answer: a) realloc()
realloc(ptr, newsize) resizes the block pointed to by ptr. It may return the same pointer (in-place resize) or a different one (moved to a larger free region). Always capture the return value — the old pointer becomes invalid after a successful realloc. This is why you should never do ptr = realloc(ptr, newsize) without checking for NULL first.
malloc()
Q8. What happens if malloc fails to allocate memory in C?
Answer: a) It returns NULL
malloc returns NULL when it can't satisfy the request (out of memory, block too large, etc.). Dereferencing NULL is undefined behaviour and usually crashes. Always check: if (p == NULL) { perror("malloc"); return 1; }. This is the single most important defensive habit in dynamic memory code.
Q9. Why should you check for NULL after calling malloc()?
Answer: a) To verify memory was successfully allocated
malloc can fail — returns NULL. Dereferencing NULL leads to crashes or worse (silent corruption on embedded systems). The NULL check is a "did my allocation succeed?" gate. It doesn't prevent leaks (that's free), doesn't deallocate (that's free), and doesn't initialize (malloc doesn't zero memory). It's purely a safety check.
Q10. How is memory alignment maintained for malloc-allocated memory?
Answer: c) By the C library, which returns suitably aligned memory for any type
malloc returns memory aligned for any fundamental type (typically 8 or 16 bytes on modern systems). This means a malloc'd block can safely store an int, a double, a struct, or even a SIMD vector without alignment issues. You don't need to align manually — the allocator does it for you. This is one reason malloc is a bit slower than stack allocation.
Q11. What does malloc(0) return in C?
Answer: b) A unique non-dereferenceable pointer (or NULL) — implementation-defined
The C standard says malloc(0) may return NULL, or a unique pointer that can be passed to free but must not be dereferenced. The behaviour is implementation-dependent. Never call malloc(0) in real code — if you don't know the size you need, handle the case explicitly. This is a subtle portability gotcha that comes up in interviews.
Q12. Is casting the return value of malloc() required in C?
Answer: b) No — C allows implicit conversion from void*
In C, void* converts implicitly to any pointer type, so int *p = malloc(...) compiles fine. In C++, casting is required. Many C style guides discourage the cast even though it's legal, because if you forget to #include stdlib.h, the compiler will assume malloc returns int and silently truncate the pointer — the cast hides this bug. Modern linters catch it either way, but the "don't cast in C" rule of thumb remains popular.
calloc()
Q13. What does calloc() do in C?
Answer: a) Allocates memory and initializes all bytes to zero
calloc(n, size) allocates n × size bytes and zeroes them out before returning. This is the key difference from malloc — malloc leaves the memory uninitialized (garbage), while calloc gives you clean memory. Use calloc when you need zero-initialized data (like arrays of counters or flags) and don't want to manually memset.
Q14. What is the difference between malloc and calloc in C?
Answer: d) calloc initializes memory to zero; malloc does not
Both allocate memory from the heap. The key difference: calloc zeroes the memory before returning it (this is guaranteed by the standard), while malloc leaves it uninitialized. calloc is slightly slower because of the zeroing, but safer if you need clean memory. Both return NULL on failure. Option a) has it backwards — a common trick in exam questions.
Q15. What is the correct syntax of calloc() in C?
Answer: a) void *calloc(size_t nmemb, size_t size);
calloc takes two arguments: number of elements and size of each element. So calloc(10, sizeof(int)) allocates 10 ints and zero-initializes them. This is different from malloc, which takes one argument (total bytes). Option c) is close but uses int instead of size_t (fine for small values but not standard). Option d) is closer to realloc's signature.
Q16. Which function should be used to allocate a contiguous zeroed array of elements in C?
Answer: b) calloc()
calloc is the natural choice for array allocation that needs zero initialization. int *arr = calloc(10, sizeof(int)); gives you 10 ints, all 0. You could achieve the same with malloc + memset, but calloc is cleaner and lets the allocator optimize (some allocators return zeroed pages from the OS without extra work). Use malloc only if you'll overwrite the memory immediately anyway.
realloc()
Q17. What is the primary use case for realloc() in C?
Answer: b) To resize an existing memory block
realloc(ptr, newsize) is specifically for resizing. Common use case: a dynamic array that grows as you add items. arr = realloc(arr, (n + 1) * sizeof(int)) expands the array by one slot. If newsize is smaller, the block shrinks. If ptr is NULL, realloc acts like malloc. If newsize is 0, behaviour is implementation-defined (often like free).
Q18. Can realloc() reduce the size of a memory block?
Answer: a) Yes — it can grow or shrink the block
realloc handles both directions. Passing a smaller size truncates the block (the tail is discarded or marked reusable). Passing a larger size grows it, possibly by moving the block to a new location. Many beginners assume realloc only grows — it works both ways. Just remember: on success, the original pointer may be invalid (moved), so update your variable with the return value.
Q19. What happens to the original block if realloc() fails?
Answer: a) The original block remains unchanged (and realloc returns NULL)
This is a critical safety property: if realloc fails (returns NULL), the original block is untouched — you can still use the old pointer. This is why the safe pattern is:
void *newptr = realloc(ptr, newsize);
if (newptr == NULL) { /* handle error, keep old ptr */ }
else { ptr = newptr; }
Never write ptr = realloc(ptr, ...) — if it fails, you lose your original pointer and leak the memory.
Q20. What is the correct way to safely resize a dynamically allocated array in C?
Answer: c) void *tmp = realloc(arr, newsize); if (tmp) arr = tmp;
This is the safe idiom. Capturing realloc into a temporary means that if it fails (returns NULL), you still have the original arr intact. Option a) leaks the original block on failure, because arr would be overwritten with NULL. Option b) discards the return value, so the resized block is unreachable (leak). Option d) frees the block and then passes a dangling pointer to realloc — undefined behaviour. Option c) is the only safe pattern.
Q21. What does realloc(NULL, size) do in C?
Answer: b) Behaves like malloc(size)
The C standard explicitly says realloc with a NULL pointer is equivalent to malloc(size). This lets you write a grow-loop that starts with a NULL pointer and calls realloc each time without special-casing the first iteration:
int *arr = NULL;
for (int i = 0; i < n; i++) arr = realloc(arr, (i+1) * sizeof(int));
Note: still capture the return into a temp and check for NULL for safety.
free() & Memory Leaks
Q22. How do you deallocate a dynamically allocated array when it's no longer needed?
Answer: b) Using free(arr)
free(arr) releases the array back to the heap. delete is C++ only. realloc(arr, 0) is technically implementation-defined and not recommended. Assigning NULL to the pointer only loses the reference — the memory is still allocated (leak). free is the correct answer, always followed by setting arr = NULL to prevent use-after-free.
Q23. What does free() do to the pointer variable after being called?
Answer: c) Nothing — the pointer still contains the old address
free() releases the memory, but it can't modify the caller's pointer because it receives it by value. The pointer still holds the address of the freed block — that's a dangling pointer. Any subsequent use of it is undefined behaviour. Always set the pointer to NULL after free: free(p); p = NULL;. This is one of the most-asked interview questions in dynamic memory.
Q24. How can memory leaks be avoided in C?
Answer: a) Always deallocate memory after use
Every malloc/calloc/realloc must have a matching free. Track every allocation carefully, free it on every code path (including error paths), and consider running Valgrind or AddressSanitizer to catch leaks. Avoiding dynamic memory entirely (option b) isn't realistic for real programs. Ignoring leaks (option c) leads to out-of-memory crashes in long-running programs.
Q25. What happens if you free the same pointer twice?
Answer: b) Undefined behaviour — may crash or corrupt the heap
Double-free corrupts the allocator's internal bookkeeping, which can crash now or corrupt unrelated allocations later. Some allocators catch double-free (glibc prints an error), but you can't rely on it. Setting the pointer to NULL after free prevents this: free(NULL) is safely a no-op, so a second free on a NULLed pointer does nothing.
Q26. What is a memory leak in C?
Answer: b) Memory that is allocated but never freed
A memory leak is allocated memory that becomes inaccessible because the pointer was lost (overwritten, out of scope, etc.) without being freed. The OS reclaims it when the program exits, but during a long-running program, leaks accumulate and eventually exhaust available memory. Option a) is a buffer overflow, c) is use-after-free, d) is uninitialized read. All four are bugs but different kinds.
Q27. How can memory leaks be identified in C programs?
Answer: d) All of the above
There's no single perfect tool, so combine approaches: static analyzers (clang-tidy, cppcheck) catch obvious patterns at compile time; manual review catches logic errors tools miss; and runtime tools (Valgrind, AddressSanitizer, LeakSanitizer) detect leaks that only show up during execution. Real codebases use all three.
Q28. What is a dangling pointer?
Answer: c) A pointer to memory that has been freed or gone out of scope
Dangling pointers point to memory that no longer belongs to you — either because it was freed or because a local variable went out of scope. Reading or writing through them is undefined behaviour. Prevention: set pointers to NULL after free, never return pointers to local variables, and never use a pointer after its target has been freed.
Q29. How can memory fragmentation be reduced in C?
Answer: c) By freeing memory blocks when they are no longer needed and reusing them efficiently
Fragmentation happens when free memory is scattered in small chunks that can't satisfy a large request. Reduce it by: freeing memory promptly (not at program exit), using pools or arenas for same-sized allocations, growing arrays in powers of 2 rather than one at a time, and avoiding mixed sizes of blocks. It's a real problem in long-running servers and embedded systems.
Q30. Why should dynamic memory allocation be used sparingly in C?
Answer: b) It can lead to memory leaks, fragmentation, and slower performance
Dynamic memory is powerful but comes with costs: allocator overhead (each malloc has bookkeeping), heap fragmentation, potential leaks, and slower access than the stack (because of cache misses). Use stack allocation when the size is known and small; reserve the heap for large or runtime-sized data. Option a) is wrong — malloc is typically slower than auto/stack. Option d) is wrong — dynamic memory uses more (metadata overhead per block).
Error Handling & Common Bugs
Q31. What will the following code do?
int *p = malloc(5 * sizeof(int)); memset(p, 0, 5 * sizeof(int));
Answer: a) Allocate memory for 5 integers and initialize them to zero
malloc allocates 5 × sizeof(int) bytes (garbage). Then memset writes zero bytes across the whole block, effectively zero-initializing it. This pattern is exactly what calloc does in one step — which is why "calloc(5, sizeof(int))" is often a cleaner choice than malloc + memset. But the given code does work as long as the malloc succeeded (missing NULL check).
Q32. When using malloc, what should you do before using the allocated memory?
Answer: b) Check if the allocation was successful (NULL check)
The first thing to do after malloc is check for NULL. If it's NULL, don't use the memory at all — handle the error. Initializing with memset (option a) is optional (depends on whether you need zeroed memory). Casting (option d) is optional in C. Freeing (option c) is the last thing, not the first. The NULL check is non-negotiable.
Q33. What is the purpose of the sizeof operator when calling malloc?
Answer: a) To determine the number of bytes to allocate
malloc takes a byte count, so you must compute the size in bytes. sizeof(type) gives the size of one element; multiply by the number you need: malloc(10 * sizeof(int)). This idiom is portable — it works even if int's size varies (2 bytes on some systems, 4 on most). Hardcoding 40 bytes would break on systems where int is not 4 bytes.
Q34. When using dynamic memory allocation in C, how can memory corruption be avoided?
Answer: c) By carefully managing allocation, bounds, and deallocation
Memory corruption comes from: writing past bounds (buffer overflow), using after free, double-free, uninitialized reads, and dangling pointers. Preventing it requires discipline across the whole lifecycle: check allocation, respect bounds, initialize before read, free exactly once, NULL after free. No single trick prevents all corruption — it's a discipline. Tools like AddressSanitizer help catch what you miss.
Q35. What happens if the free() function is called with a NULL pointer?
Answer: c) Nothing happens — free(NULL) is safely a no-op
The C standard explicitly says free(NULL) has no effect. This is why setting a pointer to NULL after free is such a good habit — accidental double-free becomes a harmless no-op instead of heap corruption. It's one of the few places where C is defensive by default. Make use of it.
Q36. What does the following code return when there is insufficient memory?
int *p = (int *)calloc(1000000, sizeof(int));
Answer: b) NULL
Both calloc and malloc return NULL when allocation fails. This is why you always check — 1,000,000 ints is 4 MB, which is fine on modern systems, but if you were asking for 4 TB, calloc would return NULL and you'd need to handle the error. Without a check, dereferencing NULL is undefined behaviour and usually a crash.
Q37. What is the correct way to use a dynamically allocated struct through a pointer?
Answer: a) struct Point *p = malloc(sizeof(struct Point)); p->x = 10;
Option a) is the correct pattern: declare a pointer, allocate with sizeof, and access members via the arrow operator. Option b) is wrong — malloc returns a pointer, not a struct value. Option c) passes a type name (not a value) to malloc. Option d) has incorrect sizeof argument (missing sizeof) and *.p.x would parse as *(p.x) which is wrong. The arrow operator p->x is shorthand for (*p).x.
Q38. What does realloc(ptr, 0) do in C?
Answer: b) Implementation-defined — often frees ptr, but don't rely on it
The C standard says behaviour is implementation-defined when realloc is called with size 0. In practice, most implementations free the block and return NULL. But that's not guaranteed, and using the return value after is unsafe. The correct idiom if you want to free is to call free(ptr) explicitly. This is a subtle portability gotcha that catches even experienced programmers.
Q39. What is the most important thing to remember when using malloc/free in a program?
Answer: b) Every allocation must have exactly one matching free on every code path
This rule of thumb prevents most dynamic memory bugs. Every successful malloc, calloc, or realloc must eventually be freed exactly once — including on error paths. Forgetting this is a leak; doing it twice is undefined behaviour. Design functions so that ownership is clear: either the caller owns the returned pointer, or the function frees it internally. A little discipline prevents almost all bugs.
Q40. Which of the following best describes the correct lifecycle of dynamically allocated memory in C?
Answer: a) malloc → use → free → set pointer to NULL
Option a) is the complete safe lifecycle: allocate, use within bounds, free exactly once, and NULL the pointer to prevent accidental reuse. Option b) uses after free (dangling pointer). Option c) is a double-free. Option d) uses memory that hasn't been allocated. Memorize the pattern — it's the single most important takeaway from dynamic memory in C.
Frequently Asked Questions
What is the difference between malloc and calloc in C?
malloc(size) allocates size bytes and leaves the memory uninitialized (garbage). calloc(n, size) allocates n × size bytes and initializes all bytes to zero. calloc is slightly slower because of the zeroing, but safer if you need clean memory. Both return void* (or NULL on failure). Use calloc when you need zeroed memory; use malloc when you'll overwrite it immediately.
Why must I check for NULL after malloc?
malloc returns NULL when it fails (out of memory, oversized request). Dereferencing a NULL pointer is undefined behaviour and usually crashes. Always check the return value before using the pointer — it's the single most important defensive habit in dynamic memory code. Without it, your program may crash at the worst possible moment.
What happens if I call free twice on the same pointer?
Double-free is undefined behaviour — it can crash immediately, silently corrupt the heap, or appear to work until a later crash. Set the pointer to NULL after free; free(NULL) is safely a no-op. This one-line habit prevents most double-free bugs and is worth adopting universally.
Why doesn't free set my pointer to NULL?
free() takes the pointer by value, so it has no way to modify the caller's variable. It only releases the memory. If you want to be safe against use-after-free, set the pointer to NULL yourself after every free call: free(p); p = NULL;. This is a two-line pattern that every C programmer should internalize.
Is it safe to cast the return value of malloc?
In C, casting is unnecessary because void* converts implicitly to any pointer type. It's also discouraged because forgetting to include stdlib.h with a cast hides a real bug (malloc implicitly returns int, which can truncate the pointer). In C++, casting is required. Many C style guides advise against casting. Modern code often skips the cast; either is fine as long as you're consistent.
💡 Tip: Dynamic memory questions are almost always testing the same few ideas: NULL check after allocation, safe realloc idiom (capture return in temp), set pointer to NULL after free, and know the difference between malloc and calloc. If you can write those four patterns from memory, you'll ace almost every dynamic memory question in exams and interviews.