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

Double-freeing a pointer

Double-freeing a pointer

What you'll learn: How to avoid the dangerous crash caused by attempting to release the same block of memory more than once.

The library book analogy

Imagine you go to a library and check out a book. When you’re finished, you return it to the front desk. The librarian puts it back on the shelf for someone else to use.

Now, imagine you walk back to the desk five minutes later and try to "return" that same book again, even though you no longer have it. The librarian would be confused, the records would get scrambled, and the system might break down.

In C, calling free() is like returning that book. The memory is handed back to the system. If you call free() on the same pointer a second time, you are "double-freeing." This isn't just a minor mistake; it’s a critical error that usually causes your program to crash instantly or, worse, creates a security hole that hackers can exploit.

Why it happens

A double-free usually occurs because of messy logic or complex loops. If two different parts of your code think they are "in charge" of the same pointer, they might both try to clean it up.

Once free(ptr) is called, the memory address stored in ptr is no longer yours. However, the variable ptr still holds that address! It becomes a "dangling pointer." If you call free() again, the memory manager tries to release memory that is already marked as available or is already being used by another part of your program.

Seeing it in code

Here is how a double-free occurs and the standard way to prevent it:

#include <stdlib.h>

int main() {
    int *data = malloc(sizeof(int) * 10);
    
    // ... use the memory ...

    free(data); // First free: The memory is returned.
    
    // CRASH WARNING:
    // free(data); // Calling this again would cause a double-free error.

    // THE FIX:
    data = NULL; 

    // Safe: free(NULL) does nothing and will not crash.
    free(data); 

    return 0;
}

The "Set to NULL" rule

The simplest way to stay safe is to immediately set your pointer to NULL after you free it. In C, calling free(NULL) is explicitly defined as doing nothing. It is a "no-op." By resetting the pointer, you ensure that even if your code accidentally tries to free the memory again, the program will remain stable.

Key takeaway

Always set a pointer to NULL immediately after calling free() to prevent accidental double-free crashes.