Memory Leaks & Common Pitfalls
Prerequisites: Dynamic memory allocation
A memory leak happens when allocated memory is never freed —
the program loses every reference to it, so it can never be
reclaimed until the process itself exits.
void leaky(void) {
int *p = malloc(100 * sizeof(int));
// ... no free(p) before p goes out of scope — leaked!
}
A short-lived program leaking a little memory may never visibly
matter; a long-running server doing this repeatedly will eventually
exhaust available memory. The rule of thumb: every successful
malloc/calloc/realloc needs exactly one matching free,
on every code path, including early returns and error handling.
Common mistakes
- Returning early from a function after an error, skipping a
free()call further down that was meant to run in every case.