Topics / C Programming / Q25
What is the difference between malloc, calloc, realloc and free?
Short answer: malloc(n) allocates n bytes with uninitialised contents. calloc(count, size) allocates count * size bytes, zeroed, and checks the multiplication for overflow. realloc(p, n) resizes a block, possibly moving it to a new address. free(p) releases a block; free(NULL) does nothing.
int *a = malloc(10 * sizeof *a); /* garbage values */
int *b = calloc(10, sizeof *b); /* all zero */
if (a == NULL || b == NULL) { /* handle failure */ }
int *tmp = realloc(a, 20 * sizeof *a); /* keep the old pointer until success */
if (tmp == NULL) { free(a); /* error */ }
else a = tmp;
free(a);
free(b);
a = b = NULL; /* avoid dangling pointers */
Details worth mentioning
reallocmay move the block: any other pointers into the old block are now invalid.p = realloc(p, n);is a classic leak: ifreallocfails, it returnsNULLand the original block is lost.realloc(NULL, n)behaves likemalloc(n).realloc(p, 0)is implementation-defined (and deprecated in C23), so do not rely on it to free.malloc(0)may return NULL or a unique pointer; do not dereference it.- Write
sizeof *prather thansizeof(int)so the size stays correct if the type changes. - Every allocation must be freed exactly once: double free and use-after-free are undefined behaviour and common security bugs.
Why many embedded projects avoid the heap
- Fragmentation: after many allocations and frees of different sizes, free memory is split into pieces too small to use, and an allocation fails even though plenty of memory is free in total. On a device that must run for years, this is a real failure mode.
- Non-deterministic timing: allocation time depends on the heap state, which is a problem for real-time code.
- Failure handling: what does an airbag controller do if
mallocreturns NULL?
MISRA C and many safety standards ban dynamic allocation after initialisation. Alternatives: static allocation, fixed-size memory pools (allocate and free in O(1), no fragmentation), and allocating everything once at start-up.