将指针强制转换为void *然后与NULL比较是否安全? [英] Is it safe to cast a pointer to void* then compare to NULL

查看:125
本文介绍了将指针强制转换为void *然后与NULL比较是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做作业,并且由于我们的约束条件非常严格,所以如果我想100%的话,我需要在所有地方检查 NULL 指针。所以我做了一个内联函数,用于检查 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);
    }
}

现在我问自己这样做安全吗?从标准中我知道将指针投射到 void * 并返回并接收原始指针是省钱的。这是否意味着该指针的 void * 版本仍然与 NULL 相当,还是我可以运行一些陷阱?在?例如,以下条件是否始终正确?

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指针

6.3.2.3 Pointers

4将空指针转换为另一种指针类型将产生该类型的空指针。任何两个空指针都应相等。

4 Conversion of a null pointer to another pointer type yields a null pointer of that type. Any two null pointers shall compare equal.

这篇关于将指针强制转换为void *然后与NULL比较是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆