Search code examples
c++pointersmemoryheap-memorydangling-pointer

What's the difference between delete-ing a pointer and setting it to nullptr?


Is saying delete pointer and pointer = nullptr the same? Probably not, but does the latter free up memory? What about delete pointer; pointer = nullptr / pointer = nullptr; delete pointer? Why not use that to make a safe way to delete pointers prematurely if required, where they would normally be deleted some other time and cause an error with a normal delete?


Solution

  • It is not the same, because while you may be setting the pointer to null, the contents that the pointer pointed to would still be taking up space.

    Doing

    delete pointer;
    pointer = NULL;
    

    Is fine, but

    pointer = NULL;
    delete pointer;
    

    Is not, since you already set the pointer to NULL, the delete command will have nothing to delete (or so it thinks). You now have a memory leak because whatever the pointer pointed to beforehand (let's say a linked list) is now floating somewhere in your memory and is untrackable by the program.