delete automatic int variable

19,371

Solution 1

delete and delete[] should only be used with pointers which you allocated explicitly with new or new[], respectively. In particular, for every time you use new, you should have a corresponding delete. Similarly, each new[] needs a corresponding delete[]. You should never use either of these with variables for which you do not explicitly allocate memory. The compiler takes care of memory allocation (and deallocation) for all non-pointer variables.

Solution 2

delete is for releasing the memory in heap allocated by new operator, and delete[] is the counterpart for new[]. You cannot use delete to release a pointer which was not allocated by new, even a pointer from malloc.

Share:
19,371
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I am trying to learn the best habits and practices in C++, particularly surrounding memory management. I have been spoiled on this front by using ARC in my iOS apps, and the built-in GC in Java, as well as a few other languages where GC is enabled.

    I understand that you use delete or delete[] to deconstruct pointers. My question is, how do you delete integers, or other variables of a base data type?

    My first thought was that since delete seems to only work with pointers, can I do this:

    int intToDelete = 6;
    delete &intToDelete;
    

    So basically, can you create a pointer to an integer in memory, and delete the integer using that pointer?

  • Pavel Ognev
    Pavel Ognev over 11 years
    You CAN use delete[] for malloc()-allocated memory in most implementations of C++ because it's just overridden free() for basic types. But it's better not to rely on this.