Course contentsShow
← C
Lesson 550 of 1,2198. Memory ManagementFree lesson

Definition of a memory leak

Definition of a memory leak

What you'll learn: Understand how forgetting to release heap memory creates "dead" space that your program can no longer use.

The Lost Key Analogy

Imagine you go to a hotel and ask for a room. The receptionist gives you a key, and that room is now yours to use. In C, this is what happens when you call malloc(). The system marks a block of memory as "reserved" for you.

Now, imagine you leave the hotel but lose the key in a drain on the way out. You didn't check out, so the hotel thinks you are still there. They won't give that room to anyone else, but since you lost the key, even you can't get back in. That room is now "leaked"—it is occupied, unusable, and unreachable.

How it happens in C

A memory leak occurs when you allocate memory on the heap and then lose the pointer that tracks its address without calling free(). Once the pointer is gone (perhaps it was a local variable in a function that finished), you have no way to tell the computer to let that memory go.

#include <stdlib.h>

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

    // We do some work here...

    // The function ends! 
    // The variable 'ptr' lives on the stack and is destroyed.
    // However, the memory it pointed to stays reserved on the heap.
    // We have no way to 'free' it now because we lost the address.
}

Why it matters

One small leak won't crash your computer. However, if your program runs for a long time—like a web server or a video game—and leaks memory inside a loop, it will slowly consume all the available RAM. Eventually, your program (or the entire operating system) will run out of memory and crash.

Memory leaks are particularly "sneaky" because they don't cause immediate errors. Your code might work perfectly for ten minutes, only to fail two hours later when the system finally runs out of breath.

Key takeaway

A memory leak is heap memory that is still "reserved" by the system but can no longer be accessed or freed because your program lost the pointer to its address.