r/C_Programming • • 2h ago

Why is Double-Free undefined behavior?

I'm wondering what the reasoning is for leaving double-freeing of memory as undefined behavior? I've run into it on a project and I'm getting runtime errors reporting the double free. I suppose from where I'm sitting (with my very limited C experience), I would have expected that freeing memory that has previously been freed (and not since reallocated) would be a no-op.

Maybe I'm misunderstanding how memory allocation works. But in a very oversimplified way my understanding is that the pointers that free expects are the ones that correspond to the beginning of a dynamically allocated block of memory. And when one uses malloc (realloc or calloc), the allocator allocates the memory you need and gives you a pointer to the start of it. With that understanding I would have thought free could only have two outcomes. Either the pointer doesn't point to the start of an allocated block, and nothing happens. Or it does and the memory is freed.

Any insight would be greatly appreciated!

Also as an aside, does free only work with [m/c/re]alloc? Or can it free other allocators as well.

17 Upvotes

26 comments sorted by

View all comments

15

u/ralphpotato 2h ago

Most of the time when these kinds of things are undefined behavior it’s so that the implementation isn’t constrained any more than it needs to to fulfill the contract. There are a lot of ways a memory allocator can work, and C basically wants to allow for as little overhead as possible regarding bookkeeping.

In most implementations, it’s likely that there’s enough bookkeeping on the allocator side that a double free is probably a no-op, in the same way that a lot of the times memory you’re given is already zeroed out even if it wasn’t specifically guaranteed. But forcing the allocator to ensure that a double free is a no-op could constrain some implementations, especially on some of the weird platforms that C was meant to accommodate.

In general it just goes with the overall C philosophy to do less bookkeeping by default and let the caller keep track of what it needs to. Double freeing is likely a logic bug in most programs anyway. If you’re writing something where you intend to allow for this, free(NULL) is explicitly a no-op for this purpose. If your program has 2 pointers to the same location and they both at some point call free() it almost certainly means these parts of the program weren’t aware who owned the lifetime of that memory and that’s very bad.