简体   繁体   中英

Is it safe to cast a pointer to void* then compare to NULL

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

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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM