Why deleteing a pointer twice will cause crash? [duplicate]
开发者_如何学GoPossible Duplicate:
Why Free crashes when called twice
I just want to know what exactly happened when we delete the pointer that already been deleted, and what cause the crash?
It's hard to predict exactly what will happen -- it depends a little on the compiler, and a lot on the standard library. Officially, it's just undefined behavior, so nearly anything can happen.
The most common thing that'll happen is that the heap will get trashed. It may not check that what delete is valid, so when it gets two blocks at the same address it may (for example) still treat them as two separate blocks, so when you allocate memory later you may get that same block of memory twice. In some other cases, it may (for example) just complement a bit to say whether that block of memory is in use, so the second time you delete it, you actually end up marking it as being in use again, so that memory can never be allocated again, and you've basically just created a leak.
If you buy a car, can you sell it twice? No right, because second time you are no longer the owner of it. When you delete the pointer for the first time , you are relinquishing your ownership and the memory will be going back to the free pool getting ready to be given out again. If you delete it for the second time, that memory might be used by any other program now and when they try to access it it will crash. Hope this is helpful
It just does.
It's illegal to free memory that you don't own (and if you previously freed a block of memory then you no longer own it).
Because it's illegal to do, the internal algorithms don't waste time double-checking memory ownership every time you try to free something, assuming that you're wise enough to just not do it.
Of course, the side effect of this is that you can mangle your memory and make things go haywire.
Analysis of really specific examples is hugely out of scope of Stack Overflow or, indeed, sanity. This answer to a possible duplicate question does a pretty good job, though.
Why can't free()
just check its "records" each time? Because C++ is designed on the principle of not doing stuff that it doesn't need to. If you're a sane programmer, you don't call free()
twice on the same block of memory, so why would you want your program to waste time and resources on pointless checks? You wouldn't. The principles of the language (and, indeed, common sense) dictate that these checks are not performed automatically.
Sidenote — I'm being a bit generous with my use of the term "illegal". Within the scope of C++, it's merely "Undefined Behaviour". Within the scope of practicality, that might as well be the same darned thing.
精彩评论