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

Final memory leak check and cleanup

Final memory leak check and cleanup

What you'll learn: How to ensure every byte of dynamically allocated memory in your data store is properly released before the program exits.

The "Borrower's Debt"

Think of malloc like checking out books from a library. Your data store "borrows" memory from the heap to hold records. If your program finishes but forgets to return those books (using free), those books remain stuck in a bin where nobody else can use them. In a long-running application, these "lost books" pile up until the system runs out of space. This is a memory leak.

For your final project, a clean exit is just as important as a working feature. You must traverse your entire data structure—whether it’s an array of pointers or a linked list—and release each piece of memory in the reverse order it was created.

Implementing the Cleanup Loop

In a data store, you usually have two levels of memory: the container (like a pointer array) and the items inside it (the records). If you free the container first, you lose the addresses to the records, leaving them stranded in memory forever.

Always free the "leaves" of your data tree before the "branches."

#include <stdlib.h>

typedef struct {
    char *name;
    int id;
} Record;

void cleanup_store(Record **store, int count) {
    for (int i = 0; i < count; i++) {
        // First, free the string inside the struct
        free(store[i]->name);
        // Second, free the struct itself
        free(store[i]);
    }
    // Finally, free the array that held the pointers
    free(store);
    
    printf("Memory cleared successfully.\n");
}

Verifying with Tools

Even if your code looks correct, tiny leaks can hide in edge cases (like an early return statement). This is where tools like Valgrind become your best friend. By running valgrind --leak-check=full ./your_program, the computer tracks every single byte. Your goal for this project is the "golden ticket" of C programming: a report stating: "All heap blocks were freed -- no leaks are possible."

Key takeaway

A professional C program isn't finished until every malloc has a corresponding free, ensuring the system's memory is left exactly as it was found.