- How
free(p)releases a heap block and why only the original pointer can be passed - Why setting
p = NULLafterfree(p)is the single most valuable habit in C memory management - What a memory leak is and how it accumulates
- Why use-after-free and double-free are undefined behaviour, and why they're so hard to debug
- How to free a multi-level allocation — an array of heap strings — from the inside out
Why free Matters and How It Works
When you call malloc, you're asking the C runtime for a block of memory from the heap. The runtime tracks every block it has handed out, so it can hand the same block back to a future malloc call. But it has no way of knowing when you're done with the block — C doesn't have automatic garbage collection. If you never tell the runtime you're done, it will keep the block marked as "in use" for the rest of the program's life. That's a memory leak: the bytes are allocated, unreachable from your code, and unavailable to any future allocation.
free(p) is how you tell the runtime you're done. It takes a pointer to a block that was previously returned by malloc (or calloc or realloc) and returns the block to the allocator's free list. After the call, the block's bytes may be reused for a future allocation, so p no longer points at a valid object. Any attempt to read or write through p is undefined behaviour (use-after-free), and calling free(p) a second time is also undefined behaviour (double-free). These are not "just warnings" — they're undefined behaviour, and on some systems they're silent, on others they crash, and in the worst case they corrupt the heap in ways that only show up much later.
The discipline is simple but must be followed strictly: every successful malloc gets exactly one free, called with the exact pointer value that malloc returned, and no use of the pointer after it's freed. To make the "no use after free" part enforceable, the standard idiom is to set the pointer to NULL immediately after freeing. A null pointer dereference is still undefined behaviour, but it crashes immediately and at a well-defined point — unlike use-after-free, which may run happily for hours and then produce garbage. Debugging a null dereference is a five-minute job; debugging a use-after-free can take days.
💡 In one line: Pair every malloc with exactly one free, pass the original pointer, and set the pointer to NULL immediately after freeing. For nested allocations, free the inner blocks first.
The Three Steps of Safe Deallocation
| Step | Operation | Effect |
|---|---|---|
| 1. Free with the original pointer | free(p); | The block returns to the allocator; p is now dangling |
| 2. Null the pointer | p = NULL; | Any later accidental dereference is a clean crash, not silent use-after-free |
| 3. Handle nested allocations | for (i = 0; i < n; i++) free(inner[i]); free(outer); | Inner blocks freed first, then the outer container — no leak, no use-after-free |
The first step has a subtle requirement: the pointer passed to free must be the same one malloc returned. If you moved p while using it (e.g., p++ to walk through an array), you must not pass the moved value to free — the allocator needs the block's starting address. The simplest way to avoid this is to never move the variable that will be freed; use a separate walk pointer (int *q = p;) for iterating. If you do move the pointer, restore it before free: p -= count; free(p);. But the safest thing is to keep the original pointer intact and use copies for any arithmetic.
The second step — nulling the pointer — is not strictly required for correctness of the program as written, because a program that never touches a freed pointer is fine without it. But it's a valuable defensive habit for larger programs and for future maintenance. If someone later adds a line that reads through p after the free, a null pointer makes that an immediate, traceable crash; a dangling pointer would silently read freed memory. On modern platforms with ASan (AddressSanitizer), a null dereference produces a clean report; a use-after-free produces a more subtle report that often only shows up when the freed memory has been reallocated. The null makes the bug easier to find, at essentially zero cost.
Complete C Program
Program: free a single block, then free an array of heap strings (from the inside out)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Small helper that mimics strdup: allocate a heap copy of src. */
char *dup_str(const char *src) {
size_t len = strlen(src);
char *dst = malloc(len + 1);
if (dst != NULL) {
memcpy(dst, src, len + 1);
}
return dst;
}
int main(void) {
/* ---- Part 1: free a single block ---- */
int *p = malloc(sizeof(int));
if (p == NULL) {
return 1;
}
*p = 42;
printf("Part 1: value through pointer = %d\n", *p);
free(p);
p = NULL;
printf("Part 1: after free, p = %p\n", (void *)p);
/* ---- Part 2: free an array of heap strings ---- */
const char *words[] = {"alpha", "beta", "gamma", "delta"};
int n = (int)(sizeof(words) / sizeof(words[0]));
/* Allocate an array of n string pointers. */
char **lines = malloc((size_t)n * sizeof(char *));
if (lines == NULL) {
return 1;
}
/* Allocate each inner string. */
for (int i = 0; i < n; i++) {
lines[i] = dup_str(words[i]);
if (lines[i] == NULL) {
/* Roll back the ones that succeeded. */
for (int j = 0; j < i; j++) free(lines[j]);
free(lines);
return 1;
}
}
printf("\nPart 2: dynamically allocated strings:\n");
for (int i = 0; i < n; i++) {
printf(" lines[%d] = \"%s\"\n", i, lines[i]);
}
/* Free the inner strings first, then the outer array. */
for (int i = 0; i < n; i++) {
free(lines[i]);
lines[i] = NULL;
}
free(lines);
lines = NULL;
printf("\nPart 2: all inner strings and the outer array have been freed.\n");
return 0;
}
Program Output
Part 1: value through pointer = 42
Part 1: after free, p = (nil)
Part 2: dynamically allocated strings:
lines[0] = "alpha"
lines[1] = "beta"
lines[2] = "gamma"
lines[3] = "delta"
Part 2: all inner strings and the outer array have been freed.
Part 1 demonstrates the single-block lifecycle: allocate, use, free, null. The printed pointer is (nil) — glibc's way of printing a null pointer — confirming that p is now safely nulled. Part 2 shows the nested pattern: one malloc for the array of pointers, then one malloc per string, then all the inner frees before the outer free. The order matters — freeing lines first would leak every lines[i], because their only references are inside the outer array. The program's rollback logic (freeing already-allocated lines[j] if a later allocation fails) shows the same discipline applied to error paths.
Step-by-Step Explanation
Let's walk through the single-block free and the nested free in detail.
1. What free actually does
free(p) doesn't zero the bytes — it tells the allocator that the block starting at p is no longer in use. The allocator's bookkeeping updates, and the block becomes eligible for reuse by the next malloc of a compatible size. The block's bytes may be overwritten by a later allocation, may be left untouched, or may be unmapped by the OS if the whole region is returned. There's no guarantee either way — that's why reading freed memory is undefined. From the caller's perspective, the pointer is now dangling: it points at memory the program no longer owns, and any use of it is a bug.
2. Why only the original pointer can be freed
The allocator uses the pointer to find the block's metadata (its size, its position in the allocator's structures). That metadata is stored just before the block's first byte, or in an external table keyed by the block address — either way, the allocator needs the exact start address. If you pass p + 1 to free, the allocator will either crash, corrupt its own bookkeeping, or return a block at the wrong address. The rule is: free must receive exactly the pointer value that malloc returned. If you've moved the pointer, restore it first.
3. The free-and-null idiom
free(p); p = NULL; is a two-line idiom that every C codebase should follow. The free releases the block; the null prevents any later use of p from silently reading freed memory. If a later line does printf("%d", *p), it now crashes with a null dereference — an immediate, obvious failure — instead of printing garbage or corrupting state. The failure point is exactly where the bug is, making it a five-minute fix instead of a multi-hour hunt through logs and heap dumps. This is one of the highest-value, lowest-cost habits in C memory management.
4. Memory leaks
A memory leak happens when a block is allocated and then the last pointer to it is lost — by overwriting the pointer, reassigning it, or letting it go out of scope — without freeing the block. The allocator still considers the block in use, so it can't be reused, and it's unreachable from your code. Leaks accumulate over time. A program that leaks 4 bytes per call, called once per request in a server running for weeks, can exhaust gigabytes. For short-lived programs, a leak at exit is harmless — the OS reclaims everything. But for long-running programs, leaks are a slow-motion crash. Tools like Valgrind and AddressSanitizer's leak checker catch them during testing; there's no way to catch them in production without instrumentation.
5. Use-after-free
Using a pointer after free is undefined behaviour. The block may have been reused for a different allocation, in which case reading through p returns data that belongs to the new allocation; writing through p corrupts that allocation. Or the block may still be free, in which case the reads return garbage and the writes corrupt the allocator's bookkeeping. Use-after-free bugs are notoriously hard to reproduce and diagnose because the symptom (a corrupted value in some unrelated data structure) appears long after the cause (the use-after-free). The null-after-free habit converts most of these into immediate null-dereference crashes, which are far easier to fix.
6. Double-free
Calling free(p) twice for the same p — without an intervening p = NULL — is undefined behaviour. The allocator may have already reused the block for a different allocation, and the second free will corrupt the allocator's structures or crash. Even worse, on some allocators, a double-free of a block that's still on the free list can corrupt the free-list pointers, leading to arbitrary memory corruption that may only manifest much later. The null-after-free habit prevents this too: after free(p); p = NULL;, calling free(p) a second time is free(NULL), which the C standard guarantees is a no-op. So p = NULL after free makes a subsequent double-free safe.
7. Tracing the single free
malloc(sizeof(int)) returns a pointer to a 4-byte block, say at address 0x555...a2a0. *p = 42; writes 42 into that block. printf("%d", *p) reads 42 from the block. free(p) returns the block to the allocator — its 4 bytes are now available for future allocation. p = NULL; overwrites p's value with NULL, so p no longer points anywhere. If the program were to dereference p now, it would crash, which is the desired outcome — a bug that's caught instead of a bug that silently corrupts data.
8. Tracing the nested free
After all allocations, lines points at an array of four char * pointers, each pointing at a heap string: "alpha", "beta", "gamma", "delta". There are five blocks in total: the outer array (4 × 8 = 32 bytes on 64-bit) and four string buffers (5, 4, 5, 5 bytes respectively, plus terminators). To free them:
- Free
lines[0](the "alpha" buffer), thenlines[1],lines[2],lines[3]. Eachfreereturns one string buffer to the allocator, and eachlines[i] = NULLmakes a subsequent read oflines[i]a clean crash. - Free
lines(the outer array). This returns the 32-byte array of pointers. After this,linesis dangling, solines = NULL.
The order is critical. If you free(lines) first, the four inner pointers are lost — you have no way to reach the string buffers, so they leak permanently. This is a classic "forgot to free the inner items" bug, and it's the most common memory management mistake with two-level allocations. The correct order is always: free the inner allocations, then the outer container that holds them.
9. The rollback path
The program includes a rollback branch for the case where an inner malloc fails. If lines[i] = dup_str(...) returns NULL, the loop has already allocated lines[0..i-1] and the outer lines. The rollback frees each of those before freeing lines and returning. Without the rollback, the program would exit with a leak — small in this case, but the same pattern applied to a long-running program would accumulate. The rule is: any error path after a successful allocation must free everything that was allocated before the error. This is easy to forget, so it's worth structuring the code so error paths are explicit and symmetric with the success path.
10. What about realloc?
realloc(p, new_size) is a combined "allocate, copy, free" operation. If it succeeds, it returns a pointer to the new block (possibly the same as p) and the old block has already been freed internally — don't call free on the old pointer. If it fails, it returns NULL and the old block remains allocated and unchanged — don't overwrite p with NULL, or you'll leak the original block. The safe idiom is char *tmp = realloc(p, new_size); if (tmp) p = tmp;. This means: capture the result in a temporary; if it's non-null, adopt it; if it's null, leave p alone. Assigning directly (p = realloc(p, ...)) loses the original pointer on failure.
11. How to detect leaks and misuse
Valgrind's memcheck tool detects leaks, use-after-free, double-free, and uninitialized reads. It runs the program under an emulator, so it's slow but thorough; the report at exit lists every leaked block with a stack trace showing where it was allocated. AddressSanitizer (-fsanitize=address with GCC or Clang) does the same for use-after-free and double-free at much lower overhead (about 2x), with the tradeoff of using more memory and possibly missing leaks that Valgrind would catch. Both are essential tools for any C programmer; run your code under one of them during development, and you'll catch most memory bugs before they reach production.
12. Complexity
free(p) is O(1) for typical allocators — it looks up the block's metadata and returns it to the appropriate free list, with no work proportional to the block's size. Freeing n blocks in a loop is O(n). For the nested case, the total work is O(n) for the inner frees plus O(1) for the outer free. Memory use drops by the block sizes after each free — for the array of four strings, freeing them reduces the program's heap usage from roughly (4 × sizeof(char *)) + (4 strings) to (4 × sizeof(char *)) after the inner frees, and to zero after the outer free.
🎯 Remember this: One malloc → one free. Pass the original pointer. Null the pointer after freeing. Free inner allocations before outer containers. Never use a pointer after free, never free the same block twice, never free a pointer you didn't get from malloc. These five rules cover almost every memory-management bug in C.
Frequently Asked Questions
1. What is the difference between a memory leak and use-after-free?
A memory leak happens when a block is allocated and never freed — the bytes stay reserved for the program's lifetime, unavailable to future allocations. The program's memory usage grows slowly and can eventually exhaust the heap. Use-after-free happens when a block is freed and then read or written through a pointer to it — the pointer is dangling, and the bytes may now belong to a different allocation. The program's behavior is undefined: it might work, might crash, might silently corrupt data. Leaks are a resource problem (you run out of memory); use-after-free is a correctness problem (your data gets corrupted). Both are serious, but use-after-free is often harder to find because the symptom can appear far from the cause.
2. Why is calling free twice a problem?
Because the second free acts on a block that has already been returned to the allocator — its metadata may have been overwritten, its bytes may have been reused for a different allocation, and the allocator's internal structures (its free lists) may have been updated to reflect a different state. Freeing it again corrupts those structures, possibly in ways that manifest as arbitrary memory corruption much later in the program. On some allocators, a double-free can be exploited by an attacker (a classic heap-corruption vulnerability). The null-after-free habit prevents it: after free(p); p = NULL;, a second free(p) is free(NULL), which the C standard defines as a no-op. So p = NULL is worth doing exactly for this safety.
3. Why free the inner strings before the outer array?
Because freeing the outer array destroys the only references to the inner strings. If you free lines first, the four char * values (pointers to the "alpha", "beta", "gamma", "delta" buffers) are gone — you no longer have any way to reach the four buffers to free them. They leak permanently. Freeing from the inside out — every lines[i] first, then lines — is the correct order, and it generalizes to any nested allocation: free the deepest blocks first, working outward.
4. Is free(NULL) safe?
Yes. The C standard explicitly guarantees that free(NULL) does nothing. This is a useful property: it means you can call free(p) without checking p != NULL, and it means the null-after-free idiom makes a subsequent double-free a harmless no-op. Many standard library functions have similar guarantees for null arguments (e.g., realloc(NULL, size) behaves like malloc(size)), which makes defensive code a bit simpler. That said, some style guides still prefer an explicit if (p) free(p); because it makes the null-check visible — but the semantics are the same.
5. Can I free a stack variable or a string literal?
No. free must only be called on pointers returned by malloc, calloc, or realloc. Passing a stack address (int x; free(&x);) is undefined behaviour — the allocator will try to look up metadata that doesn't exist, usually crashing or corrupting its own state. Passing a string literal (free("hello")) is also undefined — the literal is in read-only memory, not on the heap. And passing an interior pointer (a pointer into the middle of a block, like p + 1) is undefined for the same reason. The rule is strict: only the exact pointer returned by the allocation function.
6. What is the time complexity of free?
free(p) is O(1) for typical allocators — it looks up the block's metadata using the pointer, then adds the block to the appropriate free list, which is a constant-time operation. The total work is independent of the block's size. Freeing n blocks in a loop is O(n). Freeing a nested structure — an outer array of m pointers, each pointing at a block — is O(m) for the inner frees plus O(1) for the outer, so O(m) total. The space complexity is negative from the allocator's perspective: each free reduces the program's heap usage by the block's size (modulo allocator bookkeeping overhead, which is constant per block).
💡 Tip: Once this works, run the program under Valgrind (valgrind --leak-check=full ./a.out) or compile with AddressSanitizer (gcc -fsanitize=address -g prog.c). Both should report "no leaks" and "no errors" for the final version of the program. Then deliberately introduce a bug — comment out one of the inner frees, or comment out the p = NULL after freeing and add a subsequent *p read — and rerun. Seeing the tools catch the bug you planted is the best way to learn what they detect and what their reports look like. This practice — plant a bug, watch the tool catch it — is how professional C programmers build intuition for memory-safety tooling.