views:

2754

answers:

6

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

   int nAmount;
   delete &nAmount;

or

class sample
{
public:
    sample();
    ~sample() { delete &nAmount;}
    int nAmount;
}
+26  A: 

no. You must only call delete on things created by new.

EDIT: Expanding this a bit, 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 nothing (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).

Mr Fooz
Thanks! My compiler didn't seg fault but I was definitely suspicious if it was legitimate.
unistudent
happy programming
Mr Fooz
In your edits, can we replace each "should" with "must".
Daniel Paull
"Should" is a better word. "Must" implies that the malloc/new/new[] will fail if the free/delete/delete[] is absent, which is not the case. The use of "exactly one" carries the implication I think you are going for.
Zooba
+3  A: 

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.

yjerem
+3  A: 

Keep in mind that when you allocate a block of memory using new (or malloc for that matter), the actual block of memory allocated will be larger than what you asked for. The memory block will also contain some bookkeeping information so that when you free the block, it can easily be put back into the free pool and possibly be coalesced with adjacent free blocks.

When you try to free any memory that you didn't receive from new, that bookkeeping information wont be there but the system will act like it is and the results are going to be unpredictable (usually bad).

Ferruccio
+1  A: 

No, Memory allocated using new should be deleted using delete operator and that allocated using malloc should be deleted using free. And no need to deallocate the variable which are allocated on stack.

Vinay
A: 

here the memory is allocated using stack so no need to delete it exernally but if you have allcoted dynamically

like int *a=new int()

then you have to do delete a and not delete &a(a itself is a pointer), because the memory is allocated from free store.