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 }
|