Is it possible to delete a non-new object?

c++, destructor, memory-management, new-operator

Solution

Yes, there will be adverse effects.

You must not `delete` an object that was not allocated with `new`. If the object was allocated on the stack, your compiler has already generated a call to its destructor at the end of its scope. This means you will call the destructor twice, with potentially very bad effects.

Besides calling the destructor twice, you will also attempt to deallocate a memory block that was never allocated. The `new` operator presumably puts the objects on the heap; `delete` expects to find the object in the same region the `new` operator puts them. However, your object that was not allocated with `new` lives on the stack. This will very probably crash your program (if it does not already crash after calling the destructor a second time).

You'll also get in deep trouble if your `Object` on the heap lives longer than your `Object` on the stack: you'll get a dangling reference to somewhere on the stack, and you'll get incorrect results/crash the next time you access it.

The general rule I see is that stuff that live on the stack can reference stuff that lives on the heap, but stuff on the heap should not reference stuff on the stack because of the very high chances that they'll outlive stack objects. And pointers to both should not be mixed together.

Problem

I have an object with a vector of pointers to other objects in it, something like this: ``` class Object { ... vector<Object*> objlist; ... }; ``` Now, Objects will be added to list in both of these ways: ``` Object obj; obj.objlist.push_back(new Object); ``` and ``` Object name; Object* anon = &name; obj.objlist.push_back(anon); ``` If a make a destructor that is simply ``` ~Object { for (int i = 0; i < objlist.size(); i++) { delete objlist[i]; objlist[i] = NULL; } } ``` Will there be any adverse consequences in terms of when it tries to delete an object that was not created with new?

Original source