Losing the last pointer to a block
What you'll learn: How a memory leak occurs when you accidentally overwrite or lose the only address pointing to an allocated memory block.
The "Leash" Analogy
Imagine you are walking a dog in a park. The dog represents a block of memory you’ve allocated on the heap, and the leash is your pointer variable. As long as you have the leash in your hand, you have control over the dog; you can bring it home or let it go when you are finished.
A memory leak happens when you drop the leash while the dog is still in the park. The dog is still there, taking up space, but you no longer have any way to reach it or tell it to leave. In C, if you lose the last pointer to a piece of malloc()'d memory without calling free() first, that memory becomes "orphaned." It stays occupied until your program ends, but your code can never use it or clear it again.
Overwriting your only map
The most common way this happens is by assigning a new address to a pointer before freeing the old one.
#include <stdlib.h>
int main() {
// 1. Allocate memory for an integer
int *data = malloc(sizeof(int));
*data = 42;
// 2. Overwrite the pointer with a new allocation
// We never called free(data) first!
data = malloc(sizeof(int));
// The address of the first block (holding 42) is now gone forever.
// We have no way to free it. This is a memory leak.
free(data); // This only frees the SECOND block.
return 0;
}
Scope and Exit
Another way to lose a pointer is through scope. If you allocate memory inside a function and store the address in a local variable, that variable is destroyed when the function ends. If you didn't return that address to the caller or free it before the closing brace }, the memory remains "checked out" from the system with no one left to check it back in.
To prevent this, always ensure every malloc() has a clear path to a free(). If you are going to repurpose a pointer variable, make sure you have either freed the memory it was pointing to or copied that address to another "leash" first.
Key takeaway
A memory leak occurs the moment you lose the last copy of a pointer's address before calling free().