How to check if void pointer points to NULL?

68,765

Solution 1

I'd simply write if (!ptr).

NULL is basically just 0 and !0 is true.

Solution 2

A NULL pointer is a pointer that isn't pointing anywhere. Its value is typically defined in stddef.h as follows:

#define NULL ((void*) 0)

or

#define NULL 0

Since NULL is zero, an if statement to check whether a pointer is NULL is checking whether that pointer is zero. Hence if (ptr) evaluates to 1 when the pointer is not NULL, and conversely, if (!ptr) evaluates to 1 when the pointer is NULL.

Your approach if (*(void**)ptr == NULL) casts the void pointer as a pointer to a pointer, then attempts to dereference it. A dereferenced pointer-to-pointer yields a pointer, so it might seem like a valid approach. However, since ptr is NULL, when you dereference it, you are invoking undefined behavior.

It's a lot simpler to check if (ptr == NULL) or, using terse notation, if (!ptr).

Share:
68,765
pyrrhic
Author by

pyrrhic

Updated on July 16, 2022

Comments

  • pyrrhic
    pyrrhic almost 2 years

    So if you do:

    void *ptr = NULL;
    

    What is the best way to check if that void pointer is NULL?

    My workaround for now is this:

    if (*(void**)ptr == NULL) ... 
    

    But this doesn't seem like the best way, as I'm implicitly assuming ptr is of type void** (which it isn't).

  • verbose
    verbose almost 11 years
    @EricPostpischil you're right of course, and I've edited accordingly. Thanks for the correction.
  • fadedbee
    fadedbee almost 10 years
    Not on all architectures, you will be writing non-portable code. It might have been the 286, when using segment addressing, where NULL != 0, but that was many decades ago.
  • jacekmigacz
    jacekmigacz about 8 years
    I would compare ptr with NULL; like ptr == NULL. There is no guarantee that NULL is equal 0.
  • Himanshu Shekhar
    Himanshu Shekhar over 7 years
    Is that approach advisable in the present world, modern machines?
  • user694733
    user694733 about 7 years
    @jacekmigacz That makes no difference. ptr == NULL is same as ptr == 0 is same as !ptr. Even if implementation uses NULL which is not all bits zero, it's still guaranteed that compiler will make all three above behave the same.
  • user694733
    user694733 about 7 years
    This is C question. C doesn't have reinterpret_cast.