-2

Suppose I have a pointer to MyClass:

MyClass *myPointer = new MyClass();

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

Thanks

KelvinS
  • 2,870
  • 8
  • 34
  • 67

3 Answers3

8

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.

Starl1ght
  • 4,422
  • 1
  • 21
  • 49
2

delete myPointer frees the allocated space but lets you with a dangling pointer (one that points to something not allocated).

myPointer = NULL set your pointer to a value that is used to represent the concept of (pointing to nothing) but gives you a memory leak in return as you didn't deallocate a memory which is now "lost". Memory leak may not be too harmful if you don't abuse, but is always considered as a kind of programming error.

You may use the following idiom to prevent future problems:

delete myPointer;
myPointer = NULL;
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
1

Briefly, delete is used to deallocate memory for an object previously allocated with the new keyword. The object's destructor is called before the object's memory is deallocated (if the object has a destructor).

Pointers that dereference the deallocated memory (usually) have not a NULL value after calling delete, but any operation on them cause errors.

Setting a pointer to NULL implies that it does not dereference anything, but the memory allocated for your object still persist.

Sometimes could be useful to set pointers to NULL after deleting object they dereference, so that it's possible to check if they are still valid (dereference a consistent memory area) or not.

Andre
  • 186
  • 11