Kelvin Salton Kelvin Salton - 5 days ago 5
C++ Question

What is the difference between delete a pointer and set the pointer as NULL?

Suppose I have a pointer to MyClass:

MyClass *myPointer = new MyClass();


What is the difference between
delete myPointer;
and
myPointer = NULL;
?

Thanks

Answer

delete myPointer de-allocates memory, but leaves value of myPointer variable, that it is pointing to some garbage address.

myPointer = NULL only sets value of myPointer to null-pointer, possibly leaking memory, if you don't delete other pointer, which points to same address as myPointer

In ideal world you should use both those strings, like this:

delete myPointer; // free memory
myPointer = nullptr; // setting value to zero, signalizing, that this is empty pointer

But overall, use std::unique_ptr, which is modern approach to memory management.

Comments