unistudent unistudent - 1 year ago 95
C++ Question

Calling delete on variable allocated on the stack

Ignoring programming style and design, is it "safe" to call delete on a variable allocated on the stack?

For example:

int nAmount;
delete &nAmount;


class sample
~sample() { delete &nAmount;}
int nAmount;

Answer Source

No, it is not safe to call delete on a stack-allocated variable. You should only call delete on things created by new.

  • for each malloc or calloc, there should be exactly one free.
  • For each new there should be exactly one delete.
  • For each new[] there should be exactly one delete[].
  • For each stack allocation, there should be no explicit freeing or deletion (the destructor is called automatically, where applicable).

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download