c++pointersnull

Is (p == NULL) the same as (*p == 0) in C++?


My C++ code has the following:

 if (p == NULL || *p == 0)

I wonder if this is redundant?

Is (p == NULL) the same as (*p == 0)? Why or why not?


Solution

  • p == whatever compares the value of p to whatever.

    *p == whatever dereferences p and compares the pointee to whatever.


    When p is a null pointer then dereferencing it is undefined.

    *p can equal 0 when p points at a memory location where the value 0 is stored.


    Are they the same? No.

    Why? Because the value of a pointer is not the value of the pointee.


    The code assumes that p is either a valid pointer or a null pointer. It checks if it is a null pointer, if not it can continue to dereference it.

    Making that assumption is rather common, however it is not safe. There are many invalid pointers that are not null and cannot be dereferenced. The better alternative is to not use raw pointers in the first place.