Ignoring programming style and design, is it \"safe\" to call delete on a variable allocated on the stack?
For example:
int nAmount;
delete &am
An angel loses its wings... You can only call delete
on a pointer allocated with new
, otherwise you get undefined behavior.
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, 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.
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.