我有这个代码:
int* ptr = 0; void* buffer = malloc( 10 * sizeof( *ptr ) );
问题是 – 在sizeof()中是否有一个空指针解引用(和UB)?
C 03 5.3.3 / 1说sizeof运算符产生其操作数的对象表示中的字节数.操作数是一个表达式,它不被评估,也可以是括号的类型.
链接到答案引用这个或类似的措辞,并利用“不评估”部分来推断没有UB.
然而,在这种情况下,我无法找到标准链接评估是否具有UB.
是否“不评估”应用sizeof的表达式使得在C中的sizeof内取消引用null或无效指针是合法的?
解决方法
在这种具体情况下,我认为我们有证据显示了什么意图.从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
这是有点投机的,因为问题还没有解决.