What happens in a double delete?
Solution 1
It causes undefined behaviour. Anything can happen. In practice, a runtime crash is probably what I'd expect.
Solution 2
Undefined behavior. There are no guarantees whatsoever made by the standard. Probably your operating system makes some guarantees, like "you won't corrupt another process", but that doesn't help your program very much.
Your program could crash. Your data could be corrupted. The direct deposit of your next paycheck could instead take 5 million dollars out of your account.
Solution 3
It's undefined behavior, so the actual result will vary depending on the compiler & runtime environment.
In most cases, the compiler won't notice. In many, if not most, cases, the runtime memory management library will crash.
Under the hood, any memory manager has to maintain some metadata about each block of data it allocates, in a way that allows it to look up the metadata from the pointer that malloc/new returned. Typically this takes the form of a structure at fixed offset before the allocated block. This structure can contain a "magic number" -- a constant that is unlikely to occur by pure chance. If the memory manager sees the magic number in the expected place, it knows that the pointer provided to free/delete is most likely valid. If it doesn't see the magic number, or if it sees a different number that means "this pointer was recently freed", it can either silently ignore the free request, or it can print a helpful message and abort. Either is legal under the spec, and there are pro/con arguments to either approach.
If the memory manager doesn't keep a magic number in the metadata block, or doesn't otherwise check the sanity of the metadata, then anything can happen. Depending on how the memory manager is implemented, the result is most likely a crash without a helpful message, either immediately in the memory manager logic, somewhat later the next time the memory manager tries to allocate or free memory, or much later and far away when two different parts of the program each think they have ownership of the same chunk of memory.
Let's try it. Turn your code into a complete program in so.cpp:
class Obj
{
public:
int x;
};
int main( int argc, char* argv[] )
{
Obj *op = new Obj;
Obj *op2 = op;
delete op;
delete op2;
return 0;
}
Compile it (I'm using gcc 4.2.1 on OSX 10.6.8, but YMMV):
russell@Silverback ~: g++ so.cpp
Run it:
russell@Silverback ~: ./a.out
a.out(1965) malloc: *** error for object 0x100100080: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap
Lookie there, the gcc runtime actually detects that it was a double delete and is fairly helpful before it crashes.
Solution 4
While this is undefined:
int* a = new int;
delete a;
delete a; // same as your code
this is well defined:
int* a = new int;
delete a;
a = nullptr; // or just NULL or 0 if your compiler doesn't support c++11
delete a; // nothing happens!
Thought I should post it since no one else was mentioning it.
Solution 5
The compiler may give a warning or something, especially in obvious (like in your example) but it is not possible for it to always detect. (You can use something like valgrind, which at runtime can detect it though). As for the behaviour, it can be anything. Some safe library might check, and handle it fine -- but other runtimes (for speed) will make the assumption you call is correct (which it's not) and then crash or worse. The runtime is allowed to make the assumption you're not double deleting (even if double deleting would do something bad, e.g. crashing up your computer)
purepureluck
Updated on February 26, 2021Comments
-
purepureluck about 3 years
Obj *op = new Obj; Obj *op2 = op; delete op; delete op2; // What happens here?
What's the worst that can happen when you accidentally double delete? Does it matter? Is the compiler going to throw an error?
-
paulsm4 over 12 yearsYes, it can matter. No, the compiler isn't going to "throw an error". Just don't do it :)
-
Steve Jessop over 12 yearsI would think in practice the worst that can plausibly happen is that some time later, the memory allocator misbehaves. This (a) forces you to spend a very long time trying to debug it, since the symptoms are nowhere near the cause and additionally (b) creates a serious security vulnerability in the software, which your employer gets sued over, loses, goes bust, and your contract ends up owned by a guy named Clive who does house clearances at a fixed price per truckload. He forces you to work your notice period bug-fixing Japanese tentacle porn RPGs.
-
Destructor almost 9 yearsDon't and never do it. It is undefined behavior. Implementation of C++ can do anything in such cases. It might really do bad things like corrupt your heap, make arbitrary and bizarre changes to other objects on the heap & might do even worst things. If you use raw pointers it is better to set it as a null pointer after 1st delete because deleting null pointer is safe otherwise use smart pointers in modern C++.
-
Petr over 8 yearsThis is a good academical question, everyone say "don't do it" but I think OP is already aware that they shouldn't do it. It's not important if they should or not, they want to know what would happen from low level point of view, which indeed, is worth knowing in order to understand the language properly.
-
-
paul23 over 12 yearsAlso in case if there's any chance a "double delete" may happen - a smart pointer usually is the best solution.
-
Mooing Duck over 12 yearsGood answer, but I'd be happier if you made a bigger deal of the Undefined Behavior.
-
Russell Borogove over 12 yearsI'm pretty sure other answers have "undefined behavior" well covered.
-
Jesse Good over 12 yearsThe problem with this answer is that on my computer the same code runs fine with no crashes.
-
Ben Voigt over 12 yearsHere you go @Russell, an upvote for your excellent comment ;) Oh, and if you do not consider C++ "a real programming language", you are hereby invited to add it to your list of ignored tags. After that we'll all get together and crank out some machine code with a hex editor.
-
Enn Michael almost 8 yearsThere was a known case of a persons monitor lighting on fire due to undefined behavior.
-
JobHunter69 over 7 yearsCan it fix my car?
-
Nikola Malešević about 6 yearsI think most people know what double delete results in - unexpected behaviour. But this answer is the best in describing what happens behind the curtains and why we actually see that crash caused by two deletes. +1
-
Jerry Jeremiah almost 6 yearsIt really could wipe your hard drive in some cases: kristerw.blogspot.com/2017/09/…
-
Michael Krebs over 5 yearsI tried the OP's example, just to see the result. I did not experience a runtime crash. On the other hand, my office building began breathing cheese. Be warned: anthyding can hadplen!
-
Miral over 5 yearsYou only get an immediate runtime crash if you are very lucky. More often, you will delete some other innocent object or otherwise trash memory that has been reused, thereby killing the puppies. (And perhaps being otherwise completely undetectable until your program does something weird that might not be a crash at some unknown time in the future.) The worst part is that it cascades -- if the double delete did successfully delete another unintended object, when eventually that object does reach its intentional deletion it will be another double deletion, and you've killed more puppies.
-
Vlad about 4 yearsSo I wonder why compiler doesn't assign nullptr to the pointer after delete. Is this for exposing double-delete bugs? What is the actual value of the pointer after deletion?
-
Enn Michael about 4 years@Vlad The value of the pointer after delete is the same as it was before the delete — in other words, the address within the pointer is still the same, except the data at that address has now been freed. (Therefore, attempting to access that data by dereferencing the pointer is undefined behaviour.) The reason why the compiler doesn't automatically assign nullptr to deleted pointers is likely both for historical and performance reasons.
-
Ben Voigt over 3 years@EnnMichael: Actually after delete there are no guarantees about the address stored inside the pointer used to delete it or any other pointer to the same object. It could be left the same as it was before. It could be changed to nullptr. You don't know, and according to the Standard you can't know, because even reading a value (without dereferencing) from such an invalid pointer is UB.
-
Pnelego over 3 yearsthis is beautiful