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;
}
No, it is not safe to call delete
on a stack-allocated variable. You should only call delete
on things created by new
.
malloc
or calloc
, there should be exactly one free
. new
there should be exactly one delete
. new[]
there should be exactly one delete[]
. In general, you cannot mix and match any of these, e.g. no free
-ing or delete[]
-ing a new
object. Doing so results in undefined behavior.