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