Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if void pointer points to NULL?

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).

like image 293
pyrrhic Avatar asked Aug 18 '13 05:08

pyrrhic


4 Answers

I'd simply write if (!ptr).

NULL is basically just 0 and !0 is true.

like image 65
nmaier Avatar answered Oct 12 '22 05:10

nmaier


Be sure to include a definition of NULL.

   #include <stddef.h>

   void  *X = NULL;

   // do stuff

   if (X != NULL)  // etc.

If you include <stdio.h> and similar then stddef.h gets pulled in automatically.

Finally, it is interesting to look at the definition of NULL in stddef.h and by doing this you will see why your initial guess at what to do is interesting.

like image 42
JackCColeman Avatar answered Oct 12 '22 04:10

JackCColeman


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).

like image 40
verbose Avatar answered Oct 12 '22 05:10

verbose


If your code manages to compile when assigning void *ptr = NULL, then it stands to reason that a simple if statement to compare if it is NULL should suffice, particularly because NULL would have to be defined if the code can compile.

Example of sufficient way to check:

if(ptr==NULL)
{
    rest of code...
}

I wrote a little test program, compiled with gcc on linux, which works:

int main()
{
    void *ptr = NULL;
    if(ptr==NULL)
    {
        return 1;
    }
    return 0;
}
like image 28
xt454 Avatar answered Oct 12 '22 05:10

xt454