Memory Leak
A memory leak is an allocation that is never freed and is no longer reachable. The process keeps the bytes until it exits. A long-running program grows without bound.
Detailed Explanation
p = malloc(n); p = malloc(n); leaks the first block: no pointer to it remains. p = malloc(n); return; without free leaks if the caller was not given p. An error path that allocated three things and frees two leaks one. A hash table that replaces a key without freeing the old key leaks the old string.
C has no garbage collector. Reachability is not scanned. If you drop the last pointer, the bytes are gone from your program and still counted against the process. The OS reclaims them on exit. A one-shot CLI that leaks 16 bytes and exits is sloppy and usually harmless. A server that leaks 16 bytes per request dies in a week.
False leaks are allocations you stored in a still-live global or a cache. Leak detectors report them at exit unless you free them in a cleanup, or you mark them as still-reachable. Decide whether process-lifetime allocations are allowed and document them.
Detection: Valgrind --leak-check=full, ASan detect_leaks=1, macOS leaks. They print the allocation stack. That stack is the place that needed an owner.
The design fix is pairing. Every new has a free. Every push that allocates has a clear. Ownership is one name: this pointer is the owner. Copies are either not owners or are deep clones. Reference counting is possible and is how some C libraries share objects; it is easy to get a cycle. Prefer a single owner.
Code Examples
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p = malloc(sizeof *p);
if (p == NULL) {
return 1;
}
*p = 1;
printf("%d\n", *p); /* prints: 1 */
free(p); /* without this, 4 bytes leak */
return 0;
}#include <stdlib.h>
static int *make_pair(void)
{
int *a = malloc(sizeof *a);
int *b = malloc(sizeof *b);
if (a == NULL || b == NULL) {
free(a);
free(b); /* free whichever succeeded */
return NULL;
}
free(b); /* this example only returns a */
*a = 2;
return a;
}
int main(void)
{
int *p = make_pair();
if (p == NULL) {
return 1;
}
free(p);
return 0;
}Common Gotchas
Replacing a pointer without freeing the old block is the classic leak
`p = malloc(...); p = malloc(...)`.
A leak on the error path is still a leak
it becomes common if the error becomes common.
Process-lifetime tables are not leaks if you can still reach them
they are a growth policy. Bound them.
`realloc` failure without keeping the old pointer leaks the old block if you ove
`realloc` failure without keeping the old pointer leaks the old block if you overwrote it