FAQ 12.10 What happens when a pointer is deleted twice?

Catastrophe.

Suppose there is a pointer variable p. The first time delete p is executed, the object *p is safely destructed and the memory pointed to by p is safely returned to the heap. The second time the same pointer is passed to delete without a subsequent new that returned that pointer, the remains of what used to be an object at *p are passed to the destructor (which could be disastrous), and the memory pointed to by p is handed back to the heap a second time. This is likely to corrupt the heap and its list of free memory. The following example illustrates this situation.

 class Fred { }; int main() {   Fred* p1 = new Fred();   Fred* p2 = p1;   delete p1;   delete p2;                                         <-- 1 } 

(1) Delete the same pointer twice: DISASTER!



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net