不评估应用sizeof的表达式是否合法取消引用C中sizeof中的null或无效指针?

首先,我看到了 this question about C99,而C99标准草案中接受的答案参考操作数没有被评估.我不知道这个答案适用于C 03.还有 this question about C++一个接受的答案,引用了类似的措辞,而且在某些情况下,出现了不确定的操作数.未评估的操作数未被评估.措辞.

我有这个代码

int* ptr = 0;
 void* buffer = malloc( 10 * sizeof( *ptr ) );

问题是 – 在sizeof()中是否有一个空指针解引用(和UB)?

C 03 5.3.3 / 1说sizeof运算符产生其操作数的对象表示中的字节数.操作数是一个表达式,它不被评估,也可以是括号的类型.

链接到答案引用这个或类似的措辞,并利用“不评估”部分来推断没有UB.

然而,在这种情况下,我无法找到标准链接评估是否具有UB.

是否“不评估”应用sizeof的表达式使得在C中的sizeof内取消引用null或无效指针是合法的?

解决方法

我相信这个标准现在在 What is the value category of the operands of C++ operators when unspecified?这样的许多问题上已经不明确了.我不认为这是有意的,像hvd指出,这对委员会来说可能是显而易见的.

在这种具体情况下,我认为我们有证据显示了什么意图.从GB 91 comment from the Rapperswil meeting说:

It is mildly distasteful to dereference a null pointer as part of our specification,as we are playing on the edges of undefined behavIoUr. With the addition of the declval function template,already used in these same expressions,this is no longer necessary.

并提出了一个替代表达式,它指的是这个不再是标准的表达式,但可以在N3090中找到:

noexcept(*(U*)0 = declval<U>())

这个建议被拒绝了,因为它没有引起未定义的行为,因为它不被评估:

There is no undefined behavior because the expression is an unevaluated operand. It’s not at all clear that the proposed change would be clearer.

这个理由也适用于sizeof,因为它的操作数被忽略.

我说不明确,但我不知道这是否由4.1 [conv.lval]涵盖,其中说:

The value contained in the object indicated by the lvalue is the rvalue result. When an lvalue-to-rvalue conversion occurs
within the operand of sizeof (5.3.3) the value contained in the referenced object is not accessed,since that operator
does not evaluate its operand.

它说所包含的值不被访问,如果我们遵循issue 232的逻辑意味着没有未定义的行为:

In other words,it is only the act of “fetching”,of lvalue-to-rvalue conversion,that triggers the ill-formed or undefined behavior

这是有点投机的,因为问题还没有解决.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...