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).
55 Answers
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 0Since 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;
} 1 I know this is a bit old post, but wanted to add something that might be useful.
What I usually do is something like this,
This is my function.
void MyMethod( const void* l_pData ///< Source data , size_t l_nLen /**< Number of bytes to convert */) { // Return if nothing is provided if (l_pData == NULL || ((const char*)(l_pData))[0] == '\0' || 0 == l_nLen) { return; } // Rest of the code
}You can check for
- Null data - Empty data - Invalid lengthFollowing are validated
MyMethod("", 10);
MyMethod(" ", 10);
MyMethod(NULL, 10);
MyMethod("valid", 0); 1