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; }
When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.
there is no way to "delete" it. It is either a global variable, with statically allocated storage, or it is a local variable with storage on the stack. As you suggest in your question, you will almost always be better off using std::vector , std::list , and the like rather than using raw C-style arrays.
A stack overflow means, as you might expect, that you exceeded the memory given to the stack. Since the stack is typically allocated its own pages, going outside the stack walks outside a valid mapped memory address.
Well, let's try it:
jeremy@jeremy-desktop:~$ echo 'main() { int a; delete &a; }' > test.cpp jeremy@jeremy-desktop:~$ g++ -o test test.cpp jeremy@jeremy-desktop:~$ ./test Segmentation fault
So apparently it is not safe at all.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With