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;
}
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;
}
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).
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.
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).
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.