Interview Q&A · C · 12 questions in this topic

Dynamic Memory Management — C Interview Q&A

All C topics

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

Example.cc
#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

Example.cc
/* 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

Example.cc
int *tmp = realloc(buf, new_n * sizeof *tmp);
if (!tmp) { /* buf still valid: handle error, original intact */ }
else { buf = tmp; /* refresh every derived pointer */ }

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits