The Analogy: Renting a Storage Unit
Local variables are your own desk. The space is yours automatically, it is small, and it is cleared the moment you leave the room — you never think about it, and you cannot take any of it with you.
The heap is a storage depot across town. You walk up and ask for a unit of whatever size you need, decided on the spot rather than when the building was designed. The clerk hands you a key, which is a pointer. The unit is yours until you hand the key back, which is free. Three things follow directly:
- Lose the key and the unit stays rented forever. That is a memory leak — the space is unusable and unreachable.
- Return the key twice and the depot's records are corrupted. That is a double free, and it damages the allocator itself, so the crash usually appears in some unrelated later allocation.
- Use the key after returning it and you are opening a unit that now belongs to someone else. That is use-after-free, and it is the bug most likely to be silently exploitable.
The depot also has no idea what you put in the unit. It hands over uninitialised space, and it never checks whether what you store fits.
Syntax or Core Structure
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t n = 5;
int *a = malloc(n * sizeof *a); /* sizeof *a, not sizeof(int) */
if (a == NULL) {
fprintf(stderr, "out of memory\n");
return 1;
}
for (size_t i = 0; i < n; i++) a[i] = (int)(i * i);
/* Grow to 8. Never assign realloc's result straight back into a. */
int *grown = realloc(a, 8 * sizeof *grown);
if (grown == NULL) {
free(a); /* a is still valid on failure */
return 1;
}
a = grown;
for (size_t i = n; i < 8; i++) a[i] = (int)(i * i);
n = 8;
for (size_t i = 0; i < n; i++) printf("%d ", a[i]);
putchar('\n');
free(a);
a = NULL; /* no stale key left behind */
return 0;
}
Output:
0 1 4 9 16 25 36 49
Two habits in that code are worth adopting before anything else. sizeof *a reads as "the size of one thing a points at", so if the type of a ever changes from int to long, the allocation follows automatically — sizeof(int) would not. And realloc goes into a temporary first, because when it fails it returns NULL without releasing the original block; assigning directly would overwrite your only pointer to it and leak the whole thing.
The four functions
| Call | Gives you | Contents | Notes |
|---|---|---|---|
malloc(bytes) | one block | indeterminate | fastest; you must fill it |
calloc(count, size) | one block for count items | all bytes zero | checks count * size for overflow |
realloc(p, bytes) | a block of the new size | old contents preserved up to the smaller size | may move the block; returns NULL on failure without freeing p |
free(p) | nothing | — | free(NULL) is legal and does nothing |
calloc is not just malloc plus a loop: it also validates the multiplication, which matters when the count comes from input. malloc(count * size) with a hostile count can wrap around to a small number and hand you a block far smaller than you asked for.
Technical Depth: The Five Heap Bugs
Heap bugs are a short, fixed list. Learning to recognise all five by symptom is most of what makes C manageable.
| Bug | Cause | Symptom | Detector |
|---|---|---|---|
| Leak | pointer lost or free skipped on some path | memory use climbs over hours | valgrind, -fsanitize=address at exit |
| Double free | free called twice on one block | crash inside a later unrelated allocation | -fsanitize=address |
| Use after free | pointer used after free | plausible garbage, or silent corruption | -fsanitize=address |
| Overflow | writing past the requested size | a neighbouring block's data changes | -fsanitize=address |
| Invalid free | freeing a stack address or an offset pointer | immediate abort, or heap corruption | -fsanitize=address |
Notice how many rows point at the same tool. Building your development target with -fsanitize=address -g turns four of the five from mysteries into reports naming the line that allocated the block and the line that misused it.
free has exactly three rules
int *p = malloc(10 * sizeof *p);
free(p + 2); /* invalid: only the pointer malloc returned */
free(p); /* correct */
free(p); /* invalid: exactly once */
p = NULL;
free(p); /* fine: free(NULL) does nothing */
int local = 5;
/* free(&local); invalid: not a heap block */
Only the exact pointer the allocator returned, exactly once, and only for heap blocks. Setting the pointer to NULL immediately after free makes the second rule enforce itself, because a repeat call then becomes the harmless free(NULL).
realloc may move the block
int *a = malloc(4 * sizeof *a);
int *alias = a; /* a second key to the same unit */
int *grown = realloc(a, 400 * sizeof *grown);
if (grown != NULL) a = grown;
/* alias is now dangling if the block moved */
When the block cannot be extended in place, realloc allocates elsewhere, copies, and frees the original. Every other pointer into the old block — including indices you cached as pointers — is dangling afterwards. This is why an array that can grow should be reached through exactly one owning pointer.
Also worth knowing: realloc(NULL, n) behaves as malloc(n), which lets a growth routine handle the first allocation with no special case. realloc(p, 0) is best avoided — the behaviour has varied between implementations and standards. Call free when you mean free.
Growth by doubling
Growing a buffer by one element each time makes appending N items cost N copies of the whole array — quadratic. Doubling the capacity when it fills makes the average append cost constant, because the copies get rarer exactly as fast as they get more expensive. Ten pushes into a buffer that starts at 4 and doubles cost three reallocations, not ten.
Who owns it?
C cannot express ownership in the type system, so it has to live in a comment and in a naming convention:
/* Returns a heap-allocated copy the CALLER must free, or NULL on failure. */
char *dup_line(const char *src);
/* Borrows text; does not keep or free it. */
void log_line(const char *text);
Every function that returns allocated memory must say so, and every allocation should have exactly one function responsible for releasing it. Most real leaks are not forgotten free calls — they are two functions each assuming the other one owned it.
Real World Example: A Growable Array That Cannot Leak
C has no vector, so every substantial C program grows one. This is the whole pattern in forty lines: a pointer, a count, a capacity, and a push that doubles when it runs out.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *data;
size_t count; /* elements in use */
size_t capacity; /* elements allocated */
} IntVec;
/* Returns 0 on success, -1 on allocation failure.
On failure the vector is left exactly as it was -- still usable. */
int vec_push(IntVec *v, int value) {
if (v->count == v->capacity) {
size_t next = (v->capacity == 0) ? 4 : v->capacity * 2;
int *grown = realloc(v->data, next * sizeof *grown);
if (grown == NULL) return -1; /* v->data still valid */
v->data = grown;
v->capacity = next;
}
v->data[v->count++] = value;
return 0;
}
/* Safe to call twice, and safe on a zeroed vector. */
void vec_free(IntVec *v) {
free(v->data);
v->data = NULL;
v->count = 0;
v->capacity = 0;
}
int main(void) {
IntVec v = { NULL, 0, 0 }; /* the valid empty state */
for (int i = 1; i <= 10; i++) {
size_t before = v.capacity;
if (vec_push(&v, i * i) != 0) {
fprintf(stderr, "out of memory\n");
vec_free(&v); /* clean up on the error path too */
return 1;
}
if (v.capacity != before)
printf("grew: capacity %zu -> %zu\n", before, v.capacity);
}
printf("%zu values:", v.count);
for (size_t i = 0; i < v.count; i++) printf(" %d", v.data[i]);
putchar('\n');
vec_free(&v);
return 0;
}
Output:
grew: capacity 0 -> 4
grew: capacity 4 -> 8
grew: capacity 8 -> 16
10 values: 1 4 9 16 25 36 49 64 81 100
Ten pushes, three reallocations. Growing by one each time would have been ten, each copying everything before it.
Four decisions in that code are the ones that keep it leak-free, and they generalise to every resource in C.
{ NULL, 0, 0 } is a fully valid empty vector. realloc(NULL, n) acts as malloc, and free(NULL) does nothing, so the first push and the final cleanup need no special cases. Designing the zero state to be legal removes a whole class of "was it initialised?" branches.
Failure leaves the object untouched. vec_push writes v->data only after realloc succeeds, so a caller who ignores the return value still has a consistent vector rather than a dangling pointer. A function that damages its argument on failure is much harder to use correctly than one that returns an error.
vec_free nulls the fields. That makes a second call harmless and turns any use-after-free into a null dereference, which crashes immediately and visibly rather than reading recycled memory.
The error path cleans up. The return 1 inside the loop calls vec_free first. Leaks almost never live on the happy path; they live on the early returns that were added later.
Common Mistakes
- Not checking for
NULL.int *a = malloc(n * sizeof *a); a[0] = 1;crashes on the second line when the allocation failed. Every allocation gets a check.
p = realloc(p, bigger);— if it fails,pbecomesNULLand the original block is unreachable and unfreeable. Always go through a temporary.
- Freeing twice. Often two functions each believing they own the block. Set the pointer to
NULLafter freeing and give every allocation exactly one owner.
- Using memory after freeing it. The values often look right for a while, because nothing has reused the block yet. The bug then surfaces under load, in unrelated code.
- Freeing something
mallocdid not return.free(p + 2),free(&local)or freeing a pointer thatreallocalready moved. Keep the original pointer and free only that.
malloc(n * sizeof(int *))when you wantedsizeof(int). On a 64-bit build this over-allocates and hides the mistake; the reverse under-allocates and corrupts the heap.sizeof *pcannot get this wrong.
- Skipping
freeon an early return. Everyreturn,breakand error branch between the allocation and the cleanup is a potential leak. A singlegoto cleanuplabel handles them all.
- Assuming
malloczeroes the memory. It does not. Accumulating into an unzeroed block, or treating it as a string before writing a terminator, gives garbage that varies between builds. Usecallocwhen you need zeros.
Best Practices
- Write
sizeof *prather thansizeof(Type)in every allocation, so the size follows the pointer's type automatically.
- Check every allocation's result before touching the memory, and make the failure path release anything already acquired.
- Assign
reallocto a temporary, test it, and only then update the owning pointer.
- Set a pointer to
NULLimmediately after freeing it. It costs one store and eliminates double frees and most use-after-free bugs.
- Give every allocation exactly one owner, and state in a comment above each function whether it returns memory the caller must free.
- Design the all-zeroes state to be valid —
realloc(NULL, n)allocates andfree(NULL)is a no-op, so initialisation and cleanup need no special cases.
- Use
callocwhen the count comes from outside your program: it checks the multiplication for overflow, which a hand-writtencount * sizedoes not.
- Run your test suite under
-fsanitize=address -gorvalgrind --leak-check=fullbefore you believe a program is memory-clean. Every one of the five heap bugs is detectable; none is reliably visible by reading.
Practice Exercises
- Allocate, grow, release. Write a program that allocates room for 3
doublevalues, fills them, grows the block to 6 withreallocinto a temporary, fills the new slots, prints all six, and frees once. Print the block's address before and after thereallocand note whether it moved on your machine.
- Commit all five heap bugs deliberately. Write five tiny programs: a leak, a double free, a use-after-free, a four-byte overflow past the end of a block, and a
freeof a stack address. Run each normally and record what you see, then run each under-fsanitize=address -gand record the report. Note which one gave no visible symptom at all without the sanitiser.
callocversusmalloc. Allocate 16ints withmallocand print them without writing anything, then do the same withcalloc. Then writechar *dupusingmallocthat copies a string and, on purpose, forgets the terminator — describe whatprintf("%s")then does and whycallocwould have masked the bug rather than fixed it.
- Finish the vector. Add
int vec_reserve(IntVec *v, size_t need),int vec_pop(IntVec *v, int *out)andint vec_shrink_to_fit(IntVec *v)to the example. Every one must leave the vector valid on failure. Verify with-fsanitize=addressthat pushing 1000 values, popping 500 and shrinking leaks nothing.
- Read an unknown number of lines. Using
fgetsinto a fixed buffer plus a growable array ofchar *, read every line of input into a heap-allocated copy, print them in reverse order, then free every copy and the array itself. Confirm withvalgrind --leak-check=fullor-fsanitize=addressthat the total is zero bytes leaked in zero blocks, and make sure the program still cleans up correctly when the very first allocation fails (simulate it by forcing onemallocto returnNULL).