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

The 'Free after use' rule

The 'Free after use' rule

What you'll learn: How to properly release borrowed memory to prevent your program from slowing down or crashing over time.

The library book analogy

Imagine you go to a library and check out a book. The librarian (the Operating System) marks that book as "in use" and hands it to you. As long as you have it, nobody else can read it. If you finish the book but keep it hidden under your bed instead of returning it, the library eventually runs out of books. Even though the books are physically there, they are "lost" to everyone else.

In C, when you use malloc(), you are checking out a "book" of memory. The Free after use rule states that for every single time you ask for memory, you must explicitly give it back using the free() function once you are finished with it.

Why it matters: Memory Leaks

If you lose the pointer to a piece of memory before calling free(), that memory is stuck in limbo. Your program can't use it, and the computer can't give it to anyone else. This is called a memory leak. If a program leaks memory inside a loop that runs thousands of times, it will eventually gobble up all the available RAM, causing the program (or the whole computer) to freeze or crash.

The rule in action

The golden rule is: One free() for every malloc(). Think of them as a pair of brackets that must always be closed.

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

int main() {
    // 1. Borrowing the memory (The Malloc)
    int *player_scores = malloc(5 * sizeof(int));

    if (player_scores == NULL) {
        return 1; // Always check if the library was empty!
    }

    // 2. Using the memory
    player_scores[0] = 100;
    printf("First score: %d\n", player_scores[0]);

    // 3. The 'Free after use' rule
    // We are done with player_scores, so we return it.
    free(player_scores);
    
    // Safety tip: Set the pointer to NULL so we don't accidentally use it again
    player_scores = NULL;

    return 0;
}

When to free?

You should call free() as soon as you are absolutely certain you no longer need the data stored in that memory block. In small programs, this is often at the end of a function. In larger apps, it’s whenever a specific task (like loading an image or a user profile) is completed.

Key takeaway

Always pair your malloc() calls with a free() to prevent memory leaks and keep your programs healthy.