Search code examples
c++new-operatordynamic-memory-allocationdelete-operator

delete operation in C++


I don't understand what delete means.

For example, in the code below, delete ptr; so the pointer variable ptr is deleted or the memory ptr pointed to is deleted?

int *ptr = new int; 
*ptr = 7;  
delete ptr; 

Solution

  • so the pointer variable ptr is deleted or the memory ptr pointed to is deleted?

    The memory pointed to by ptr is deleted (i.e. marked as free - the contents could still be there, but, as @JonTrauntvein also mentioned, depending on the implemetation that memory could be overwritten with a certain pattern as well - it should never be accessed after a delete).

    The pointer itself doesn't change and still contains the same value (i.e. the memory address it was pointing to), but it is a good habit to null the pointer after deletion, i.e. ptr = NULL;.

    This memory was allocated on the heap with new int and should always be freed with delete.


    int *ptr = new int; 
    

    -> memory is allocated on the heap - amount: sizeof(int) - ptr points to that memory location.

    *ptr = 7;  
    

    -> the value 7 is placed in that allocated memory.

    delete ptr; 
    

    -> The allocated memory (containing 7) is deleted (i.e. marked as free for other usage). ptr still points to that freed memory location. Accessing it is invalid, so the pointer should be set to NULL.