- What dynamic memory allocation means and why C needs it
- Static vs dynamic allocation, and stack vs heap
- How
malloc,calloc,reallocandfreereally behave - Memory leaks, dangling pointers, double free, heap overflow
- How to allocate arrays, 2D arrays and linked list nodes
- The classic pitfalls interviewers look for
- How to find memory bugs with Valgrind and AddressSanitizer
This page answers the dynamic memory questions that come up in almost every technical interview for a C, systems, or embedded role. It starts with what dynamic allocation actually is, then walks through the four standard functions one at a time, then covers the bugs that interviewers love to ask about — leaks, dangling pointers, double free, heap overflow and fragmentation — and finishes with practical allocation patterns and the tools that catch these errors. Every answer is short enough to memorise and precise enough to hold up when the interviewer asks a follow-up question.
Basics of Dynamic Memory Allocation
Q1. What is dynamic memory allocation in C, and why is it important?
Answer: Dynamic memory allocation is the process of reserving memory while the program is running instead of at compile time — using malloc, calloc and realloc — and releasing it later with free.
When you declare int marks[50]; the compiler fixes the size before the program ever runs. But very often you do not know the size in advance: how many records are in the file you are about to read? How many nodes will the user add to the list? How long is the line the user types? In all those cases the size is known only during execution.
Dynamic allocation solves this by letting the program ask the operating system for a block of memory of any size at run time. The block comes from the heap, is not tied to any function's lifetime, and stays valid until you explicitly free it. That is what makes it possible to build linked lists, trees, hash tables, dynamically growing arrays and string buffers — structures whose shape and size change as the program runs.
Its importance in interviews comes from the flip side: because you own the lifetime, you are responsible for releasing it. Every leak, dangling pointer and heap overflow in a C program traces back to this manual ownership model.
Q2. What is the difference between static and dynamic memory allocation?
Answer: Static allocation is decided at compile time, has a fixed size and is released automatically; dynamic allocation is decided at run time, can be any size, and is released only by free.
| Point | Static / compile-time allocation | Dynamic / run-time allocation |
|---|---|---|
| When decided | Before the program runs (compile time) | While the program runs (run time) |
| Size | Fixed, written in the source code | Chosen at run time, can change with realloc |
| Memory area | Data segment, BSS segment, or stack | Heap |
| Released by | The compiler / runtime, automatically | The programmer, using free() |
| Speed | Faster — no allocator call | Slower — allocator bookkeeping involved |
| Typical use | Fixed-size arrays, global counters, small locals | Linked lists, trees, buffers of unknown length |
A useful way to remember it: with static allocation the compiler decides and the runtime cleans up; with dynamic allocation you decide and you clean up. That transfer of responsibility is exactly what makes dynamic allocation powerful and dangerous at the same time.
Q3. Is dynamically allocated memory stored on the stack or on the heap?
Answer: On the heap. Stack memory belongs to function calls and disappears when the function returns; heap memory returned by malloc lives until it is freed.
A C program's memory is normally divided into four regions: the text segment (the compiled code), the data/BSS segments (globals and statics), the stack (local variables and function call frames), and the heap (dynamic allocations).
- Stack: grows and shrinks automatically as functions are called and return, is very fast, and is usually limited to a few megabytes. A pointer to a local variable becomes invalid the moment the function returns.
- Heap: managed manually through
malloc/free, can grow much larger, is shared across the whole program, and allocation is slower because the allocator must find a suitable free block.
So a classic interview trap — returning the address of a local array from a function — fails because that array is on the stack. The same function returning a malloc'ed block works, because the block is on the heap and survives the return.
Q4. Which functions are used for dynamic memory allocation in C?
Answer: Four standard functions declared in <stdlib.h>: malloc, calloc, realloc and free. C11 also provides aligned_alloc.
malloc(size)— allocates one uninitialized block ofsizebytes.calloc(n, size)— allocatesnelements ofsizebytes each and sets all bytes to zero.realloc(ptr, new_size)— changes the size of an existing block, keeping its contents.free(ptr)— returns a block to the heap so it can be reused.aligned_alloc(align, size)— C11 addition that returns memory aligned to a stricter boundary, useful for SIMD and hardware buffers.
All four classic functions share the same allocator underneath, so memory obtained from any of them can be released with free, and can be resized with realloc. Forgetting to include <stdlib.h> is a common cause of mysterious warnings and 64-bit pointer truncation bugs, because the compiler then assumes these functions return int.
Q5. Why must you check the return value of malloc or calloc for NULL?
Answer: Because allocation can fail — the system may be out of memory — and it then returns NULL. Dereferencing NULL is undefined behaviour, usually an immediate crash.
int *data = malloc(n * sizeof *data);
if (data == NULL) {
fprintf(stderr, "Out of memory\n");
return -1; /* handle the failure, do not continue */
}
/* safe to use data here */
On a desktop with swap space, malloc rarely fails for small requests, which is why many beginners skip the check — and then the code crashes on an embedded board with 64 KB of RAM. On Linux, a large allocation may also succeed but be killed later by the OOM killer when pages are actually touched.
A good interview answer adds that the failure path must be consistent: if you have already allocated three buffers and the fourth allocation fails, you must free the first three before returning. That "clean up on every error path" habit is exactly what prevents leaks.
malloc, calloc, realloc and free
Q6. What is malloc() and what does it return?
Answer: void *malloc(size_t size) reserves a single block of size bytes on the heap and returns a pointer to its first byte — uninitialized — or NULL on failure.
/* Preferred idiom: sizeof on the pointed-to object */
int *p = malloc(n * sizeof *p);
/* Also correct, and slightly more explicit */
int *q = malloc(n * sizeof(int));
Two points interviewers listen for. First, the memory is not initialized: it holds whatever bytes were left there before, so reading it before writing is undefined behaviour, not "zero". Use calloc or memset if you need zeros.
Second, the return type is void *, which converts implicitly to any object pointer type in C, so the cast is unnecessary. Writing (int *)malloc(...) is legal but can hide the real bug of a missing #include <stdlib.h>: without the cast, the compiler warns about the implicit int-to-pointer conversion; with the cast, that warning disappears and a 64-bit pointer may be silently truncated.
Also note that sizeof *p is better than sizeof(int) because if the type of p ever changes, the allocation size follows automatically instead of quietly becoming wrong.
Q7. What is calloc() and what makes it different?
Answer: void *calloc(size_t n, size_t size) allocates space for n elements of size bytes each and sets every byte to zero.
/* 10 integers, all guaranteed to be 0 */
int *arr = calloc(10, sizeof *arr);
if (arr == NULL) return -1;
The name means "contiguous allocation": the total size is n * size, computed by the function itself. That matters because calloc is required to detect multiplication overflow, so calloc(SIZE_MAX, 2) fails cleanly instead of allocating a tiny block that you then overrun — a real class of security bug in hand-written malloc(n * size) code.
The zero-fill is not just cosmetic. It removes an entire category of bugs (reading uninitialized values) and is convenient for arrays of numbers, buffers, and structures whose pointer fields you want initialized to NULL. The cost is that zeroing takes time proportional to the size, so for very large blocks where you will overwrite everything anyway, malloc is cheaper.
Q8. What is the difference between malloc() and calloc()?
Answer: malloc takes one size argument and leaves memory uninitialized; calloc takes a count and an element size, multiplies them, and zero-fills the result.
| Point | malloc() | calloc() |
|---|---|---|
| Syntax | malloc(total_bytes) | calloc(count, element_size) |
| Number of arguments | One | Two |
| Initialization | None — contains garbage values | All bytes set to 0 |
| Speed | Slightly faster (no zeroing) | Slightly slower for large blocks |
| Overflow safety | You must check n * size yourself | Overflow checked internally |
| Typical use | Buffers that will be fully overwritten | Arrays and structs that start at zero |
A concise interview formulation: "Same allocation, different contract — calloc is malloc plus zeroing plus overflow checking, at the price of a slightly slower call." Both return NULL on failure and both are released with the same free.
Q9. What is realloc() and what care is needed when using it?
Answer: realloc(ptr, new_size) resizes an existing block, keeping its contents. The block may move, and on failure it returns NULL while the original block stays valid — so always use a temporary pointer.
/* WRONG: if realloc fails, the only pointer to the block is lost */
arr = realloc(arr, new_count * sizeof *arr);
/* RIGHT: keep the original address until success is certain */
int *tmp = realloc(arr, new_count * sizeof *arr);
if (tmp == NULL) {
free(arr); /* or keep using the old block */
return -1;
}
arr = tmp;
What realloc guarantees: the first min(old_size, new_size) bytes keep their values. Any newly added tail bytes are uninitialized. If the block can be grown in place the returned pointer equals the argument; otherwise the allocator copies the data to a new location and frees the old block, so any other pointer or reference into the old block becomes invalid.
That last point is the subtle one. If two pointers alias the same block and you realloc through one of them, the other may now point at freed memory. This is also why resizing in a loop should grow geometrically (double the capacity) rather than by one element: doubling makes the total copying cost linear, while growing by one each time makes it quadratic.
Q10. What does free() do and how should it be used correctly?
Answer: void free(void *ptr) returns a heap block to the allocator. It must receive the exact pointer the allocator returned, it does not modify your pointer variable, and free(NULL) is a safe no-op.
char *buf = malloc(100);
if (buf == NULL) return -1;
/* ... use buf ... */
free(buf);
buf = NULL; /* prevents accidental use-after-free and double free */
The rules that matter: free only pointers obtained from malloc/calloc/realloc; never free the address of a local or global variable; never free an interior address such as buf + 10 (that pointer was never returned by the allocator); free each block exactly once.
Setting the pointer to NULL afterwards is a discipline, not a requirement of the language — free cannot change your variable because it receives a copy of the address. But the habit is what turns a latent double-free crash into a harmless free(NULL), and it makes use-after-free fail immediately and visibly instead of silently corrupting the heap.
Memory Bugs & Common Pitfalls
Q11. What is a memory leak in C, and how can it be prevented?
Answer: A memory leak occurs when allocated memory becomes unreachable — no pointer to it remains — but is never freed, so the process keeps consuming memory until it slows down or is killed.
/* LEAK: the pointer is overwritten, the block is now unreachable */
char *msg = malloc(64);
msg = NULL; /* the 64 bytes can never be freed */
/* LEAK on the early-return path */
Node *n = malloc(sizeof *n);
if (!valid(n)) return -1; /* forgot free(n) */
free(n);
Five practical prevention rules:
- One owner per block. Decide which function or structure owns each allocation and is therefore responsible for freeing it.
- Free on every path. Error returns and
break/gotoexits are where most leaks hide; use a single cleanup label. - Set to NULL after free so a stale pointer cannot be freed again or reused.
- Null out pointers before overwriting them, especially in loops that reassign a temporary buffer.
- Test with tools. Valgrind or LeakSanitizer report exactly which
malloccall produced the leaked block.
A fair nuance for interviews: memory still allocated when main returns is reclaimed by the operating system, so a leak in a short-lived command-line tool is harmless in practice. In a server, daemon or embedded device that runs for weeks, the same leak is a fatal defect — which is why "the OS cleans up at exit" is not an acceptable answer.
Q12. What is a dangling pointer, and how do you avoid it?
Answer: A dangling pointer still holds the address of memory that has already been freed, or of a local variable that no longer exists. Reading or writing through it is undefined behaviour.
int *p = malloc(sizeof *p);
*p = 42;
free(p); /* p is now dangling ... */
/* ... later ... */
printf("%d\n", *p); /* undefined behaviour: use after free */
p = NULL; /* the fix: make the pointer obviously dead */
There are three common ways to create one: freeing a block but keeping the pointer, returning the address of a local variable, and keeping several aliases (copies) of the same pointer and invalidating them all with a single free or realloc.
The mitigations are the same three habits used against leaks: null the pointer after free, return heap memory (never the address of a local) from functions that must outlive their frame, and avoid unnecessary aliasing — if two pointers must refer to the same block, document which one owns it. In C there is no runtime check that catches this for you, which is why free(p); p = NULL; is written as a single reflex rather than two separate decisions.
Q13. What is a double free, and why is it dangerous?
Answer: A double free is calling free twice on the same block. The second call corrupts the allocator's internal free-list, which can crash immediately, crash much later, or be exploited by an attacker.
/* Dangerous: two paths both free the same block */
if (error) { free(buf); return -1; }
...
free(buf); /* double free if the branch above ran */
/* Safe: free once, then make the pointer NULL */
free(buf);
buf = NULL;
free(buf); /* free(NULL) does nothing — harmless */
The reason it is so damaging is that free writes bookkeeping data into and around the block. Freeing it twice means that metadata is processed twice, so the allocator may later hand the same memory to two different malloc calls. Two unrelated parts of the program then write to the same bytes — a corruption that surfaces far away from the actual bug.
In security terms, double free is a classic heap-exploitation primitive, which is why hardened allocators exist and why free(NULL) being a guaranteed no-op is part of the C standard: it lets defensive code null out every pointer without adding branches.
Q14. What happens if you write past the end of a heap block?
Answer: That is a heap buffer overflow. It silently corrupts neighbouring allocations or the allocator's metadata, causing crashes far from the bug — and in production it is a security vulnerability.
char *s = malloc(8);
strcpy(s, "12345678"); /* 8 chars + '\0' = 9 bytes: one byte over */
int *a = malloc(10 * sizeof *a);
a[10] = 0; /* valid indices are 0..9 */
Unlike the stack, where a large overflow usually hits a guard page and dies loudly, heap overflows often stay silent: the extra byte lands in the next block's header or payload and nothing complains until much later. That silence is what makes them exploitable — overwriting a function pointer or a saved address turns a bug into arbitrary code execution.
Defences at the source level: always allocate n + 1 for a string of n characters, prefer snprintf and bounded copies over strcpy/strcat, keep the capacity in a variable alongside the pointer, and re-check loop bounds. At the tooling level, AddressSanitizer catches the overflow at the exact instruction during testing, which is far cheaper than debugging a crash months later.
Q15. What is memory fragmentation in dynamic memory allocation?
Answer: Fragmentation is wasted memory caused by allocation patterns — external fragmentation when free memory is split into pieces too small to use, internal fragmentation when the allocator rounds requests up.
- External fragmentation: the total free memory is sufficient, but it is scattered in small gaps between live blocks, so a large request still fails. Classic cause: allocating and freeing many blocks of different sizes in an interleaved pattern.
- Internal fragmentation: the allocator rounds 13 bytes up to a 16-byte chunk for alignment and bookkeeping, so 3 bytes inside the block are unusable. Small allocations suffer most.
Practical mitigations: allocate fewer, larger blocks instead of many small ones; reuse buffers instead of repeatedly allocating and freeing them in a loop; use a pool or arena allocator for many same-sized objects (list nodes, for example); and reserve capacity in advance with realloc growing geometrically rather than one element at a time.
Fragmentation matters most on long-running systems and on embedded devices with no virtual memory to paper over the gaps. On a desktop OS the virtual memory system hides much of it, which is why the same allocation pattern that runs fine on a PC can fail on a microcontroller after a few hours.
Practical Usage & Examples
Q16. How do you allocate memory for an array, a two-dimensional array, and a linked list node?
Answer: A 1D array uses one malloc of n * sizeof *p; a 2D array uses either an array of row pointers or one flat block; a node uses malloc(sizeof *node) followed by linking.
1. One-dimensional array
int n = 10;
int *arr = malloc(n * sizeof *arr);
if (arr == NULL) return -1;
for (int i = 0; i < n; i++) arr[i] = i * i;
free(arr);
arr = NULL;
2. Two-dimensional array — array of row pointers
int rows = 3, cols = 4;
int **m = malloc(rows * sizeof *m);
if (m == NULL) return -1;
for (int i = 0; i < rows; i++) {
m[i] = malloc(cols * sizeof *m[i]);
if (m[i] == NULL) { /* free what we already have */
while (i--) free(m[i]);
free(m);
return -1;
}
}
/* free in the reverse order */
for (int i = 0; i < rows; i++) free(m[i]);
free(m);
A single flat block, int *m = malloc(rows * cols * sizeof *m); accessed as m[i * cols + j], needs only one malloc and one free, is contiguous and is therefore faster — the usual choice in performance-critical code. The row-pointer version is more convenient to index as m[i][j].
3. Linked list node
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *new_node(int value)
{
Node *n = malloc(sizeof *n);
if (n == NULL) return NULL;
n->data = value;
n->next = NULL;
return n;
}
Note sizeof *n rather than sizeof(Node): the allocation follows the pointer's type automatically. Freeing a whole list requires walking it while saving next first, because after free(cur) the next field is itself freed memory.
Q17. Why do you need strlen(s) + 1 bytes to copy a string into allocated memory?
Answer: Because strlen counts the characters but not the terminating '\0', and strcpy writes that terminator too — so allocating strlen(s) bytes causes a one-byte heap overflow.
char *dup_string(const char *s)
{
size_t len = strlen(s) + 1; /* +1 for '\0' */
char *copy = malloc(len);
if (copy == NULL) return NULL;
memcpy(copy, s, len); /* or strcpy(copy, s) */
return copy;
}
"hello" has strlen 5, but it occupies 6 bytes: h e l l o \0. Allocating 5 bytes and calling strcpy writes the 6th byte into whatever follows the block — a textbook off-by-one heap overflow. It often goes unnoticed because the byte is a zero, until the neighbour happens to be a size field or a pointer.
The same rule applies to strncpy, which does not add a terminator when the source is longer than the limit, and to snprintf, whose size argument does count the terminator. A good habit is to keep the capacity next to the pointer instead of recomputing it, so the "+1" decision is made once.
Q18. What does malloc(0) return?
Answer: It is implementation-defined: malloc(0) may return NULL, or a unique non-NULL pointer that can be passed to free but must never be dereferenced.
void *p = malloc(0);
if (p != NULL) {
/* legal: a valid pointer that must not be dereferenced */
free(p);
} else {
/* also legal: allocation of zero bytes reported as failure */
}
The C standard allows both behaviours because a zero-byte request is ambiguous: it is not an error, but there is nothing to store. glibc typically returns a unique minimum-size pointer; some embedded allocators return NULL.
Portable code should avoid the situation entirely by treating "size zero" as a case to handle before allocating — for example, returning early or allocating one byte deliberately. The dangerous pattern is code that assumes malloc(0) == NULL to detect an empty request; that assumption holds on some platforms and fails on others.
Q19. What are the most common pitfalls to avoid in dynamic memory allocation?
Answer: Not checking for NULL, forgetting to free, double free, use after free, wrong sizeof, losing the pointer when realloc fails, freeing non-heap addresses, and off-by-one overflows.
- No NULL check: the failure path either crashes or silently corrupts data.
- Memory leak: allocated but never freed, often on an error return.
- Double free: two cleanup paths freeing the same block.
- Use after free: reading or writing a block after
free, or after its owner went out of scope. - Wrong size:
malloc(sizeof(ptr))instead ofsizeof *ptr— allocates pointer size, not array size. - Losing the original pointer: assigning
reallocstraight back to the only pointer. - Freeing the wrong address:
free(&local_var)orfree(buf + offset). - Off-by-one:
nbytes for ann-character string, or indexnon an array of sizen. - Reading uninitialized memory:
mallocdoes not zero; usecallocwhen you rely on zeros. - Integer overflow in the size:
n * sizewrapping around to a small number; check before multiplying or usecalloc.
If an interviewer asks for just one, give the pair that causes the most real incidents: "freeing something twice, and never freeing at all — one corrupts the heap, the other exhausts it."
Debugging Memory Errors
Q20. How do you detect memory errors and leaks in a C program?
Answer: Compile with warnings and debug symbols, then run the program under Valgrind or build it with AddressSanitizer and LeakSanitizer — they report invalid accesses, use-after-free, double free and unreleased blocks with the source line.
/* 1. Compiler warnings first — they are free */
gcc -Wall -Wextra -g -O0 program.c -o program
/* 2. Valgrind memcheck */
valgrind --leak-check=full --show-leak-kinds=all ./program
/* 3. Or AddressSanitizer + LeakSanitizer */
gcc -g -fsanitize=address -fno-omit-frame-pointer program.c -o program
./program
Valgrind runs the binary on a synthetic CPU and tracks every byte, so it needs no recompilation but is roughly 10–50× slower. Its messages distinguish "definitely lost" (a real leak), "indirectly lost" (reachable only from a leaked block) and "still reachable" (usually a global structure, not a bug).
AddressSanitizer instruments the code at compile time. It is much faster than Valgrind and catches heap and stack overflows, use-after-free and double free at the exact instruction, printing both the free site and the bad access. LeakSanitizer runs at exit and lists every unreleased block with its allocation stack.
Beyond tools, the reliable manual checks are: read every malloc and ask "who frees this?", test the failure paths by injecting NULL returns, and run the suite under sanitizers in CI so regressions are caught on the commit that introduced them rather than in production.
Frequently Asked Questions
Is memory returned by malloc initialized to zero?
No. malloc returns raw, uninitialized memory containing whatever bytes were previously stored there. Reading it before writing is undefined behaviour. Use calloc if you need a guaranteed zero-filled block, or memset after allocating. Beginners often see zeros in practice because a fresh page from the OS happens to be zeroed, but that is an accident of the operating system, not a guarantee of the language.
Should I cast the return value of malloc in C?
No. In C, void * converts implicitly to any object pointer type, so the cast adds nothing. Worse, it can suppress the compiler warning that would have told you <stdlib.h> is missing — and without that header the compiler assumes malloc returns int, which truncates 64-bit pointers on modern systems. In C++ the cast is required, which is why so much code written by C++ programmers carries it over into C.
Can memory from calloc or realloc be released with free?
Yes. malloc, calloc, realloc and aligned_alloc all draw from the same heap allocator, so any block from any of them is released with free. What you must not do is mix allocators — memory from new in C++ with free, or memory from a custom pool allocator with the standard free. Those combinations are undefined behaviour.
Do I need to free memory before the program exits?
Strictly speaking no — the operating system reclaims all of a process's memory when it terminates. But relying on that is a bad habit. Long-running programs never "exit", so every leak accumulates; and a leak reported at exit by a tool or a code reviewer is a sign of a lifetime bug that may also bite while the program is running. Free what you allocate, and let the tool confirm a clean run.
What is a flexible array member and when is it useful?
A flexible array member is the last member of a structure declared as int data[]; with no size (C99). You allocate the structure plus as many elements as you need in a single malloc: malloc(sizeof(Header) + n * sizeof(int)). It keeps the header and its payload in one contiguous block, so a single free releases everything and there is no second pointer to track — a common technique for messages, packets and string buffers.
What is the difference between free(p) and realloc(p, 0)?
free(p) is the defined way to release a block. realloc(p, 0) has implementation-defined behaviour: historically it freed the block and returned NULL, but the standard does not guarantee that, and some implementations return a zero-size block instead. Because the result is ambiguous — and NULL looks the same as a failure — never use it as a substitute for free.
💡 Tip: If you are preparing for a C interview, memorise one reflex pair: every malloc gets a NULL check, and every free is followed by p = NULL. Those two lines eliminate the majority of the bugs interviewers probe for — leaks, dangling pointers, and double frees — and they give you something concrete to say when the follow-up question comes.