-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
  • 33,896
  • 20
  • 72
  • 119
  • 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
  • 413,367
  • 61
  • 711
  • 904
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
  • 8,705
  • 6
  • 42
  • 67
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
  • 57,599
  • 16
  • 82
  • 120