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

Leaking in loops and recursion

Leaking in loops and recursion

What you'll learn: How repetitive code structures can turn a tiny memory oversight into a program-crashing catastrophe.

The multiplication effect

In C, a memory leak occurs when you allocate memory (using malloc) but lose the pointer to it before calling free. While losing a few bytes once might not be noticed, losing those bytes inside a loop or a recursive function creates a compound interest effect that can quickly consume every byte of RAM your computer has available.

Think of a memory leak like a dripping faucet. A few drops on the floor is a minor nuisance. However, if that faucet drips every time a gear turns in a machine, and that gear turns 10,000 times a second, your house will be underwater in minutes. In programming, loops are those high-speed gears.

The loop trap

A common mistake is allocating memory inside a loop for a temporary task but forgetting to clean it up before the next iteration begins. When the loop restarts, the pointer variable is overwritten with a new address, and the previous memory block is lost forever in the heap.

#include <stdlib.h>
#include <stdio.h>

void process_data() {
    for (int i = 0; i < 1000000; i++) {
        // We allocate 1KB of memory every single iteration
        char *buffer = malloc(1024); 
        
        // ... perform some work with buffer ...

        // PITFALL: If we don't free(buffer) here, we lose 1KB 
        // every loop. By the end, we've leaked 1GB of RAM!
        free(buffer); 
    }
}

The recursive sinkhole

Recursion is even more dangerous. Because each recursive call adds a new layer to the stack, if every layer also grabs a piece of the heap and fails to release it during the "unwinding" phase, you exhaust two types of memory at once. If a recursive function calls itself 500 times and leaks a small array each time, you aren't just losing memory; you are building a graveyard of unreachable data that stays active until the entire program is forced to shut down by the operating system.

When working with repetition, always ask: "Does this allocation happen once, or every time the code repeats?" If it's every time, the free must be just as frequent.

Key takeaway

Repetitive leaks scale exponentially; always ensure your free call sits inside the same loop or recursive cycle as your malloc.