Calling delete on variable allocated on the stack

前端 未结 11 1918
遇见更好的自我
遇见更好的自我 2020-11-22 14:35

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

For example:

   int nAmount;
   delete &am         


        
相关标签:
11条回答
  • 2020-11-22 15:06

    An angel loses its wings... You can only call delete on a pointer allocated with new, otherwise you get undefined behavior.

    0 讨论(0)
  • 2020-11-22 15:09

    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.

    0 讨论(0)
  • 2020-11-22 15:09

    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.

    0 讨论(0)
  • 2020-11-22 15:12

    It's UB because you must not call delete on an item that has not been dynamically allocated with new. It's that simple.

    0 讨论(0)
  • 2020-11-22 15:13

    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.

    0 讨论(0)
提交回复
热议问题