Memory leaks and lost pointers
What you'll learn: How to avoid "losing" pointers to allocated memory, preventing your program from wasting system resources.
The hotel room analogy
Imagine you go to a hotel and rent a room. The receptionist hands you the only physical key card to that room. As long as you have that card, you can use the room, and eventually, you can return it so the hotel can rent it to someone else.
A memory leak happens if you throw that key card into a deep lake. The room is still "rented" to you in the hotel’s computer system, but you have no way to get inside or return the key. The room sits empty and unusable forever. In C, if you allocate memory using malloc() and then overwrite the pointer variable holding that address, you’ve thrown away the key.
How we lose pointers
A common mistake is assigning a new value to a pointer before freeing the old memory it was pointing to.
#include <stdlib.h>
int main() {
// 1. We grab a "key" to 40 bytes of memory
int *ptr = malloc(10 * sizeof(int));
// 2. CRITICAL ERROR: We assign ptr a new address
// The original 40 bytes are now "lost" in RAM.
// We have no way to call free() on them anymore.
ptr = malloc(20 * sizeof(int));
// 3. We can free the second allocation...
free(ptr);
// ...but the first 40 bytes are leaked until the program ends.
return 0;
}
Why it matters
Small leaks might not seem scary, but they add up. If your program runs in a loop—like a web server or a video game—and leaks a few kilobytes every second, it will eventually consume all available RAM. When this happens, the operating system will step in and crash your program to save the rest of the computer.
To stay safe, always ensure every malloc() has a corresponding free(), and never overwrite a pointer variable unless you are certain the memory it currently points to has been released or its address is stored safely elsewhere.
Key takeaway
A memory leak occurs when you lose the address of allocated memory before freeing it, making that memory unreachable and unusable.