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;
}
Nobody can know what happens. This invokes undefined behavior, so literally anything can happen. Don't do this.
Yes, it is undefined behavior: passing to
delete
anything that did not come fromnew
is UB:The consequences of undefined behavior are, well, undefined. "Nothing happens" is as valid a consequence as anything else. However, it's usually "nothing happens right away": deallocating an invalid memory block may have severe consequences in subsequent calls to the allocator.
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.
It's UB because you must not call delete on an item that has not been dynamically allocated with new. It's that simple.
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).
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.