Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; 

or

class sample { public:     sample();     ~sample() { delete &nAmount;}     int nAmount; } 
like image 524
unistudent Avatar asked Jan 14 '09 03:01

unistudent


People also ask

What happens when you call delete in C++?

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.

How do you delete a local variable in C++?

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.

What happens when we allocate space in the stack?

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.


2 Answers

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.

like image 35
Paige Ruten Avatar answered Nov 16 '22 00:11

Paige Ruten


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.

like image 109
Mr Fooz Avatar answered Nov 16 '22 00:11

Mr Fooz