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

社会主义新天地 提交于 2020-01-05 04:59:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!