Course contentsShow
← C
Lesson 1164 of 1,21916. Practice and ProjectsFree lesson

What is a memory leak?

What is a memory leak?

What you'll learn: Understand how forgetting to free heap memory creates "ghost" data that haunts your computer's RAM.

The Trillion-Room Hotel

Imagine your computer's RAM is a massive hotel with millions of rooms. When you use malloc(), you are calling the front desk and asking for a room. The clerk gives you a key (the pointer), and that room is yours to use.

In C, the hotel clerk is very trusting but also very lazy. They will never check if you are still in the room. They expect you to walk up to the desk and hand the key back using free(). If you check out of the hotel but keep the key in your pocket and drive away, the clerk still marks that room as "Occupied." Nobody else can use it, but you aren't using it either.

If you do this once, it’s no big deal. But if your program does this thousands of times per second, the hotel eventually fills up with "ghost" guests. When a new program asks for a room, the clerk has to say, "Sorry, we're full," and your computer crashes or slows to a crawl. That is a memory leak.

Losing the Map

A leak usually happens when you lose the pointer to a block of memory before calling free(). Once the pointer is gone, you have no way to tell the computer which memory you want to release. It is stuck in limbo.

#include <stdlib.h>

void create_leak() {
    // We ask for space for 10 integers
    int *secret_numbers = malloc(10 * sizeof(int));

    // We do some work here...
    secret_numbers[0] = 42;

    // ERROR: The function ends, and the local variable 'secret_numbers' 
    // is destroyed. We lost the "key" to the room!
    // We can no longer call free(secret_numbers).
}

int main() {
    while(1) {
        create_leak(); // This will eventually eat all your RAM.
    }
    return 0;
}

Why it Matters

Memory leaks are dangerous because they are "silent" killers. Your code might run perfectly for five minutes, but after five days on a server, it consumes every byte of available memory. Tools like Valgrind act like a private investigator, tracking every key you've been issued to make sure you returned them all to the front desk before the program ended.

Key takeaway

A memory leak occurs when you lose the pointer to heap-allocated memory without freeing it, making that RAM unavailable to the rest of the system.