在C中是否定义了& * NULL? [英] Is &*NULL well-defined in C?

查看:92
本文介绍了在C中是否定义了& * NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下哪个版本的C标准(如果有)中定义明确?

In what version(s) of the C standards (if any) is the following well-defined?

void foo(void) {
    char *nullPtr = NULL;
    &*nullPtr;
}

请注意,我没有将结果分配给任何内容-第二行是一个简单的语句.

Note that I am not assigning the result to anything - the second line is a simple statement.

这个应该是一个带有明显答案的问题,但是(似乎在此类问题上经常发生)我听到很多人说答案显然没有定义"为明显"定义".

This should be a question with an obvious answer, but (as seemingly happens way too often on such questions) I have heard just as many people say the answer is "obviously undefined" as "obviously defined".

相对来说,以下内容如何? foo是否应该读取c?

On a rather related note, what about the following? Should foo produce a read of c?

extern volatile char c;

void bar(void) {
    volatile char *nonnullptr = &c;
    &*nonnullptr;
}

(同一问题的C ++版本:在C ++中是否定义了& * NULL?)

(C++ version of the same question: Is &*NULL well-defined in C++?)

推荐答案

尽管尝试取消引用空指针会导致未定义的行为,所以*nullPtr是非法的,而&*nullPtr则是定义明确的. 根据C11标准草案的脚注102 :

While attempts to dereference a null pointer cause undefined behavior, so *nullPtr is illegal, &*nullPtr is perfectly well-defined. According to footnote 102 in the C11 Draft Standard:

因此,& * E 等同于 E (即使 E 是空指针),....

Thus, &*E is equivalent to E (even if E is a null pointer),....

这是因为对于一元&运算符(§6.5.3.2¶3):

This is a result of the fact that, for the unary & operator (§6.5.3.2 ¶3):

如果操作数是一元 * 运算符的结果,则不会对该运算符和& 运算符求值,并且结果好像都被省略了一样. ...

If the operand is the result of a unary * operator, neither that operator nor the & operator is evaluated and the result is as if both were omitted,....

C99标准具有相同的语言,但是在C90标准中没有出现,我对该标准的理解是&*nullPtr的确会在C99之前的实现中引起不确定的行为.

The C99 Standard has the same language, but this does not appear in the C90 Standard, and my reading of that standard is that &*nullPtr would indeed cause undefined behavior in pre-C99 implementations.

根据C90标准(第6.3.2.3节):

From the C90 Standard (§6.3.2.3):

一元& (地址)运算符的结果是指向由其操作数指定的对象或函数的指针.

The result of the unary & (address-of) operator is a pointer to the object or function designated by its operand....

和:

一元*运算符表示间接....如果为指针分配了无效值,则一元*运算符的行为是不确定的.

The unary * operator denotes indirection.... If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.

奇怪的是,我没有在

Curiously, I don't see any discussion of this change in the C99 Rationale, though I may just be not finding it.

这篇关于在C中是否定义了& * NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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