Ignoring programming style and design, is it "safe" to call delete on a variable allocated on the stack?
For example:
int nAmount;
delete &nAmount;
or
class sample
{
public:
sample();
~sample() { delete &nAmount;}
int nAmount;
}
You already answered the question yourself.
delete
must only be used for pointers optained throughnew
. Doing anything else is plain and simple undefined behaviour.Therefore there is really no saying what happens, anything from the code working fine through crashing to erasing your harddrive is a valid outcome of doing this. So please never do this.
After playing a bit with g++ 4.4 in windows, I got very interesting results:
calling delete on a stack variable doesn't seem to do anything. No errors throw, but I can access the variable without problems after deletion.
Having a class with a method with
delete this
successfully deletes the object if it is allocated in the heap, but not if it is allocated in the stack (if it is in the stack, nothing happens).An angel loses its wings... You can only call
delete
on a pointer allocated withnew
, otherwise you get undefined behavior.No, it is not safe to call
delete
on a stack-allocated variable. You should only calldelete
on things created bynew
.malloc
orcalloc
, there should be exactly onefree
.new
there should be exactly onedelete
.new[]
there should be exactly onedelete[]
.In general, you cannot mix and match any of these, e.g. no
free
-ing ordelete[]
-ing anew
object. Doing so results in undefined behavior.Well, let's try it:
So apparently it is not safe at all.