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).
I'd simply write if (!ptr)
.
NULL
is basically just 0
and !0
is true.
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.
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)
.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With