r/C_Programming • u/FernwehSmith • 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.
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.