问题
i am working on a homework and since our constraints are really strict i need to check for NULL
pointers everywhere if i want 100%. So i made a little inlined function which checks pointers for NULL
:
static inline void exit_on_null(void* ptr, const char* msg) {
if ( ! ptr ) {
printf("%s\n", msg);
exit(1);
}
}
Now i asked myself is it safe to do so? From the standard i know it is save to cast a pointer to void*
and back and receive the original pointer. Does that give that the void*
version of the pointer is still comparable to NULL
or is there some pitfall i can run in? For example is the following always true?
ptr = NULL
(void*) ptr == NULL
回答1:
I found the answer myself in the standard:
6.3.2.3 Pointers
4 Conversion of a null pointer to another pointer type yields a null pointer of that type. Any two null pointers shall compare equal.
回答2:
How do you think that's not safe? But don't do this
static inline void exit_on_null(void* ptr, const char* msg) {
if (!*(void **)ptr) {
printf("%s\n", msg);
exit(1);
}
}
// segfault
exit_on_null(NULL, "yeet");
来源:https://stackoverflow.com/questions/56510988/is-it-safe-to-cast-a-pointer-to-void-then-compare-to-null