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.

18 Upvotes

26 comments sorted by

View all comments

2

u/bothunter 2h ago

The problem is that memory could be reused by another part of the program in the time between the first free and the second free.  Which means the program just freed memory to a pointer it didn't control.  Now the other pointer is being used after it has been freed.  This will work at first, but you've started corrupting the heap in a way that is going to eventually cause a crash.  And that crash is going to be in a very different part of the program and is going to be very difficult to debug.

1

u/bothunter 2h ago

One of the things that malloc will do as an optimization is create special regions of memory for common allocation sizes to reduce fragmentation.  Which means if you happen to double-free on one of those, you actually have a very good chance of freeing a pointer that has just been allocated somewhere else. 

One of the app compatibility shims in Windows is to use an older malloc implementation that doesn't have that optimization, because some software had a bunch of double-free bugs that weren't a problem until those optimizations were added in later versions of Windows.