Dynamic Memory Management

a memory leak

Imagine renting storage lockers and, every so often, forgetting where you put a key. The locker is still locked, still reserved in your name, but you can never open it again and you cannot return it. Rent enough lockers and lose enough keys, and eventually the whole facility is full of rooms you cannot use. A memory leak is exactly this: heap memory that your program allocated but can no longer reach and will never free, so it stays reserved uselessly until the program exits.

Precisely: a leak happens when the last pointer to a heap block is lost without the block being freed. The block is still allocated — the allocator still considers it in use — but no variable in your program holds its address anymore, so there is no way to ever free it. Common ways this happens: overwriting the only pointer with a new allocation before freeing the old one (p = malloc(...) twice with no free between); returning early from a function on an error path and skipping the free; or losing a pointer when a data structure is rebuilt. Unlike a crash, a leak is silent — nothing goes wrong immediately. The program just slowly uses more and more memory.

Why it matters depends on how long the program runs. A short command-line tool that leaks a little and then exits is barely a problem, because the operating system reclaims all of a process's memory when it terminates. But a long-running program — a server, a daemon, a desktop app left open for days — that leaks a bit per request will grow without bound, slow down as it swaps, and eventually be killed when it exhausts memory. Tools like Valgrind's memcheck and the AddressSanitizer leak detector exist precisely to find the allocation whose matching free is missing.

char *p = malloc(100); p = malloc(200); /* LEAK: the first 100-byte block is now unreachable */ /* ... */ free(p); /* frees only the 200-byte block */

Overwriting the only pointer before freeing leaks the first block forever; the second free cannot reach it.

A leak is not a crash and may pass every test on a short run. It only bites long-lived programs; the OS frees everything when a process exits, which can mask leaks in tools.

Also called
leak洩漏記憶體流失