Course contentsShow
← C
Lesson 988 of 1,21914. Data Structures in CFree lesson

Freeing the dynamic array

Freeing the dynamic array

What you'll learn: How to properly release heap memory once your dynamic array is no longer needed to prevent memory leaks.

The "Borrowed Hotel Room" Analogy

Think of your computer’s RAM as a massive hotel. When you use malloc or realloc to create a dynamic array, you are essentially checking into a block of rooms. The operating system gives you a key (the pointer) and promises that no one else will use that space while you’re there.

However, the hotel doesn't have an automated checkout system. If you leave the hotel without returning the key, the front desk still thinks those rooms are occupied. They won't rent them to anyone else, even though the rooms are empty. In programming, this is called a memory leak. If your program runs for a long time and keeps "checking into rooms" without checking out, your computer will eventually run out of memory and crash.

Using the free() function

To prevent leaks, you must use the free() function. This function tells the system, "I am finished with this block of memory; you can give it to someone else now."

You only need to pass the pointer that holds the starting address of your dynamic array. Importantly, you should only free memory that was allocated via malloc, calloc, or realloc.

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

int main() {
    // 1. Request space for 5 integers
    int *scores = malloc(5 * sizeof(int));

    if (scores == NULL) {
        return 1; // Always check if allocation failed
    }

    // ... Use the array for your logic here ...
    scores[0] = 95;

    // 2. We are done with the array. Check out of the "hotel."
    free(scores);

    // 3. Safety step: Prevent "Dangling Pointers"
    scores = NULL;

    return 0;
}

The Safety Reset

Notice the line scores = NULL; after the free command. When you call free(scores), the memory is released, but the pointer scores still holds the address of that memory. This is called a dangling pointer. If you accidentally try to access scores[0] later, your program might crash or behave unpredictably. By setting the pointer to NULL, you ensure that any accidental future use of that pointer will result in a clear, debuggable error rather than a mysterious memory corruption.

Key takeaway

Always pair every malloc or realloc with a free to return memory to the system and prevent leaks.