Dangling Pointers, Leaks & Double-Free in C
Manual memory fails in three classic ways: leaks (losing the last pointer without freeing — slow resource bleed), dangling pointers (using memory after free — silent corruption or crashes far from the cause), and double-free (freeing twice — heap metadata corruption). All three hide until load, time, or allocator mood exposes them.
Defenses are systematic, not heroic: free exactly once per allocation, NULL pointers after freeing, establish single ownership per block, and run AddressSanitizer plus Valgrind regularly. In C, memory correctness is a process — allocation discipline plus tooling — not a feature.
Leaks: lost without freed
Reassigning the last pointer (p = malloc(...); twice) orphans the first block — Valgrind's definitely-lost reports find these.
Dangling: used after freed
free(p); ... *p = x; touches recycled memory — works until the allocator reuses the block, then corrupts mysteriously.
Double-free: freed twice
Two owners, one free each — heap corruption. Single ownership plus NULL-after-free eliminates the pattern.
Tool everything
-fsanitize=address in testing plus periodic Valgrind runs catch all three classes with exact locations.
#include <stdio.h>#include <stdlib.h> int main(void) { int *p = malloc(sizeof *p); if (!p) return 1; *p = 5; printf("%d\n", *p); free(p); p = NULL; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.