Interview Q&A · C · 12 questions in this topic
Dynamic Memory Management — C Interview Q&A
malloc and friends — allocation patterns, leaks, double-free, realloc discipline and valgrind-grade hygiene. Part of Dynamic Memory · 202 questions in the C bank.
What do `malloc`, `calloc`, `realloc` and `free` each do?
Answer
malloc(n) allocates n uninitialized bytes (contents indeterminate). calloc(k, n) allocates zeroed k*n bytes with overflow-checked multiplication. realloc grows/shrinks a block (possibly moving it — old pointer dies). free releases a block; free(NULL) is a safe no-op.
Always check for NULL, always pair with exactly one free, and size with sizeof(*p) so the type follows the pointer.
Example
#include <stdlib.h> int *p = malloc(100 * sizeof *p); /* uninitialized */ int *z = calloc(100, sizeof *z); /* zeroed */ free(p); free(z);
💡 Uninitialized vs zeroed vs resized vs released is the four-way split to recite.
What is the difference between `malloc` and `calloc` beyond zeroing?
Answer
calloc takes a count and element size (calloc(n, size)) and checks their product for overflow — malloc(n * size) can wrap silently into a too-small buffer. calloc zeroes, which costs time but gives deterministic contents; malloc leaves garbage, which is faster but must be fully written before reading.
Security-sensitive buffers prefer calloc (no information leak from recycled heap); hot scratch buffers prefer malloc plus explicit init.
Example
/* overflow-safe: */ size_t n = untrusted_count(); int *a = calloc(n, sizeof *a); /* NULL on overflow or OOM */ /* risky: size_t bytes = n * sizeof *a; // may wrap */
How do you use `realloc` safely?
Answer
Assign realloc to a temporary: on failure it returns NULL and the original block stays valid — assigning directly over the source pointer leaks the block on failure. After success, every old pointer/index into the block must be refreshed (the block may have moved), and sizes should be computed overflow-safely.
realloc(NULL, n) acts like malloc; realloc(p, 0) is implementation-defined — avoid it and call free explicitly.
Example
int *tmp = realloc(buf, new_n * sizeof *tmp); if (!tmp) { /* buf still valid: handle error, original intact */ } else { buf = tmp; /* refresh every derived pointer */ }
What are the classic heap bugs: leak, double-free, use-after-free, overflow?
Answer
Leak: allocated, never freed — grows until OOM (find with ASan/LSan, valgrind). Double-free: freed twice — heap metadata corruption, exploitable. Use-after-free: touched after free — UB that may read attacker-controlled recycled memory. Overflow: written past the end — corrupts neighbors, the classic security hole.
One discipline prevents all four: single owner, exactly-once free, NULL-after-free for shared handles, sizes with the buffer.
Key points
- 1Leak — missing free on some path.
- 2Double-free — ownership unclear, freed twice.
- 3Use-after-free — lifetime shorter than use.
- 4Overflow — write past the end.
Example
free(p); p = NULL; /* NULL-after-free turns reuse into a safe no-op/crash */
💡 Name all four with one-line definitions — interviewers grade the completeness of the list.
What is the difference between stack and heap allocation?
Answer
Stack (automatic storage) is scope-managed: allocation is a pointer bump, cleanup is automatic — fast and leak-proof. Heap (allocated storage) lives until free: flexible lifetime and size, but manual management, fragmentation risk and slower allocation.
C keeps values on the stack by default; heap is for unknown-at-compile-time sizes, large buffers, and lifetimes exceeding the creating scope.
Key points
- 1Lifetime — stack ends at scope exit; heap ends at free.
- 2Speed — stack bump vs allocator bookkeeping.
- 3Safety — stack cannot leak; heap leaks on every missed path.
Example
void f(size_t n) { int small[64]; /* stack: automatic cleanup */ int *big = malloc(n * sizeof *big); /* heap: must free */ /* ... */ free(big); }
What is memory layout of a C program (text, data, bss, heap, stack)?
Answer
Text holds code (read-only). Data holds initialized globals/statics. BSS holds zero-initialized globals/statics (occupies no file space). Heap grows up for malloc. Stack grows down for frames. String literals typically live in read-only data.
This map explains why globals start at zero, why stack overflow collides toward the heap, and why writing to a literal segfaults.
Key points
- 1Text — machine code, read-only.
- 2Data/BSS — initialized / zero-initialized globals.
- 3Heap/stack — dynamic growth in opposite directions.
Example
int g_init = 5; /* .data */ int g_zero; /* .bss (zero, no file space) */ /* "literal" // read-only data */
💡 Sketch the five segments in address order — that drawing answers half the memory questions.
How do you write leak-free C with manual cleanup (goto cleanup pattern)?
Answer
Initialize every handle to NULL/closed, work stepwise, and funnel all exits through one cleanup label that frees conditionally. NULL-initialization makes partial failure safe; single-exit makes every path auditable.
This goto-cleanup idiom is the C substitute for destructors — structured, reviewable, and exception-free (C has no exceptions to unwind with).
Example
int run(void) { char *buf = NULL; FILE *f = NULL; int rc = -1; buf = malloc(4096); if (!buf) goto out; f = fopen("in.txt", "r"); if (!f) goto out; rc = 0; out: free(buf); if (f) fclose(f); return rc; }
💡 NULL-init plus single cleanup label is the pattern; defend it as idiomatic C, not a goto apology.
What is memory fragmentation (internal vs external) and what mitigates it?
Answer
Internal fragmentation wastes space inside allocations (rounding up to size classes/alignment). External fragmentation scatters free memory into unusable slivers between live blocks. Mitigations: fixed-size pools/arenas for hot paths, batch allocation, freeing in reverse order, and avoiding tiny long-lived interleavings.
Long-running C services (servers, embedded) design allocation strategy upfront — the allocator is architecture, not detail.
Key points
- 1Internal — wasted inside blocks (alignment, size classes).
- 2External — wasted between blocks (unusable gaps).
- 3Fix — pools, arenas, batching, allocation discipline.
What tools find memory bugs, and what does each catch?
Answer
AddressSanitizer (-fsanitize=address): overflows, use-after-free/scope, double-free, leaks (with LSan) — fast enough for test suites. Valgrind Memcheck: same family with no rebuild, much slower. UBSan: signed overflow, aliasing, misaligned access. Static analyzers and -fanalyzer: compile-time paths.
Workflow: sanitizers in CI on every test run, valgrind for release-only repros, -Werror so warnings never reach runtime tools.
Example
/* gcc -std=c17 -fsanitize=address,undefined -g main.c -o app_dbg */💡 ASan-in-CI is the single highest-value memory practice — say it first.
How do you implement a simple arena (region) allocator in C?
Answer
Reserve one large buffer; bump a cursor on each allocation with alignment rounding; free everything at once by resetting the cursor (individual free is a no-op). Lifetimes become scoped to a request/frame — no per-object bookkeeping, near-zero per-allocation cost.
Arenas fit compilers, request handlers and game frames; they do not fit objects with genuinely independent lifetimes.
Example
typedef struct { char *base, *cur, *end; } arena_t; void *arena_alloc(arena_t *a, size_t n) { /* align up, bump, bounds-check, return */ return NULL; } /* arena_reset(&a); // frees everything at once */
What is the difference between `malloc/free` and `new/delete` (for C vs C++ interviews)?
Answer
malloc/free manage raw bytes with no type or construction knowledge; new/delete allocate plus construct/destruct. malloc returns NULL on failure while throwing-new throws; the families must never mix (malloc with delete, new with free is undefined behavior).
C programmers asked this are really being tested on what C lacks: no constructors run, no type safety net, no mismatch protection — the discipline is entirely conventional.
Example
int *a = malloc(3 * sizeof *a); /* no construction, may be NULL */ free(a); /* C++: int *b = new int[3](); delete[] b; // must match */
Should you check malloc for NULL? What do you do when it fails?
Answer
Yes — always. Allocation can fail (OOM, overcommit limits, insane sizes), and dereferencing NULL is a segfault. On failure, propagate the error up (return code), release partial state, and let the layer that can shed load or abort decide.
Never continue as if allocation succeeded; never exit() deep inside a library — return the failure to the caller.
Example
int *buf = malloc(n * sizeof *buf); if (!buf) return -1; /* propagate; caller decides */
💡 Propagate, do not exit in libraries — that boundary rule is the senior half of the answer.
Recommended resourcesAffiliate links · may earn us a commission