-1

I'm confused about why some people point a pointer (created on the heap earlier) to 0 after deleting it.

For example:

Node* newNode = new Node();

delete newNode;
newNode = 0;    // why?

Why does it matter if a deleted pointer points to 0 or to something else?

Oleksiy
  • 37,477
  • 22
  • 74
  • 122
  • 1
    This is to act as a warning to anybody reading the code. It's a shorthand way of saying: "treat this code with extra care -- the author probably didn't know or understand RAII or else completely misunderstands object lifetime." – Jerry Coffin Aug 07 '13 at 04:21

3 Answers3

5

This is done so that you'll get an immediate error if you ever accidentally try to use it after it's been deleted. Using a pointer that points to deleted memory may sometimes "work", but crash sometime later. By setting it to NULL, you make sure that it's always a bad pointer to use.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
0

You should make a pointer point it to NULL to make it invalid after deleting so that if you try to accidentally access it, you get an error.

NOTE: Earlier versions of compiler used NULL(which is practically #DEFINE NULL 0) to make pointer invalid. C++11 now has nullptr to make it invalid(which is different from NULL)

Saksham
  • 9,037
  • 7
  • 45
  • 73
0

So if further in the code you tried to delete it again you will not get an error.

Just a marker that you have done it!

Ed Heal
  • 59,252
  • 17
  • 87
  • 127