CC Explainer
C · 4 · Dynamic Memory & Data Structures19 / 35 · 54%

Leaks, Double Frees & Dangling Pointers

Every malloc needs exactly one free — on every path, including error paths.

Examples: valgrind, free(NULL), p = NULL

shortcuts: ← prev · → next · M mark
1

The Leak

Lose the last pointer to a block and the memory is unreachable forever.

Example
example
char *buf = malloc(1024);
buf = malloc(2048);   // LEAK: the first block is now unreachable
free(buf);            // frees only the second
STACKautomaticfast, LIFOsmall (~1 MB)frees on returnHEAPmanual / newlargelifetime = youfree / delete
orphaned heap block
2

Dangling Pointers

Using memory after free is undefined and often exploitable.

Example
example
free(p);
// p still holds the old address — a dangling pointer
p = NULL;    // make the mistake crash loudly instead of silently
free(p);     // free(NULL) is guaranteed safe
TIP
Set pointers to NULL immediately after freeing. free(NULL) is a documented no-op.
3

Single-Exit Cleanup

The goto-cleanup pattern keeps error paths leak-free.

Example
example
int run(void) {
    int rc = -1;
    char *a = malloc(64); if (!a) goto out;
    char *b = malloc(64); if (!b) goto out_a;

    rc = 0;
    free(b);
out_a:
    free(a);
out:
    return rc;
}
This is the one place idiomatic C really does use goto.
4

Finding Leaks

Tools, not eyeballs.

Syntax
syntax
valgrind --leak-check=full --show-leak-kinds=all ./app
gcc -fsanitize=address,undefined -g app.c -o app && ./app
Interview question
Does a leaked allocation matter if the program exits immediately?