|
||||
Section 16:
|
[16.2] Is it safe to delete the same pointer twice?
No! (Assuming you didn't get that pointer back from new in between.) For example, the following is a disaster: class Foo { ... }; void yourCode() { Foo* p = new Foo(); delete p; delete p; ← disaster! ... }That second delete p line might do some really bad things to you. It might, depending on the phase of the moon, corrupt your heap, crash your program, make arbitrary and bizarre changes to objects that are already out there on the heap, etc. Unfortunately these symptoms can appear and disappear randomly. According to Murphy's law, you'll be hit the hardest at the worst possible moment (when the customer is looking, when a high-value transaction is trying to post, etc.). Note: some runtime systems will protect you from certain very simple cases of double delete. Depending on the details, you might be okay if you happen to be running on one of those systems and if no one ever deploys your code on another system that handles things differently and if you are deleting something that doesn't have a destructor and if you don't do anything significant between the two deletes and if no one ever changes your code to do something significant between the two deletes and if your thread scheduler (over which you likely have no control!) doesn't happen to swap threads between the two deletes and if, and if, and if. So back to Murphy: since it can go wrong, it will, and it will go wrong at the worst possible moment. Do NOT email me saying you tested it and it doesn't crash. Get a clue. A non-crash doesn't prove the absence of a bug; it merely fails to prove the presence of a bug. Trust me: double-delete is bad, bad, bad. Just say no. |