gpt4 book ai didi

c++ - 取消引用一个等于 nullptr 的指针是标准未定义的行为吗?

转载 作者:可可西里 更新时间:2023-11-01 16:30:56 26 4
gpt4 key购买 nike

一位博客作者提出了关于空指针解引用的讨论:

我在这里提出了一些反驳论点:

他引用标准的主要推理是这样的:

The '&podhd->line6' expression is undefined behavior in the C language when 'podhd' is a null pointer.

The C99 standard says the following about the '&' address-of operator (6.5.3.2 "Address and indirection operators"):

The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier.

The expression 'podhd->line6' is clearly not a function designator, the result of a [] or * operator. It is an lvalue expression. However, when the 'podhd' pointer is NULL, the expression does not designate an object since 6.3.2.3 "Pointers" says:

If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

When "an lvalue does not designate an object when it is evaluated, the behavior is undefined" (C99 6.3.2.1 "Lvalues, arrays, and function designators"):

An lvalue is an expression with an object type or an incomplete type other than void; if an lvalue does not designate an object when it is evaluated, the behavior is undefined.

So, the same idea in brief:

When -> was executed on the pointer, it evaluated to an lvalue where no object exists, and as a result the behavior is undefined.

这个问题纯粹是基于语言的,我不是在问给定的系统是否允许用任何语言篡改位于地址 0 的内容。

据我所知,取消引用值等于 nullptr 的指针变量没有任何限制,甚至认为指针与 nullptr 的比较(或(void *) 0) 常量在某些情况下可能会因为所述段落而在优化中消失,但这看起来像是另一个问题,它不会阻止取消引用其值等于 的指针空指针。请注意,我已经检查了其他 SO 问题和答案,特别是 like this set of quotations ,以及上面的标准引号,我没有偶然发现从标准中清楚地推断出如果指针 ptr 比较等于 nullptr 的东西,取消引用将是未定义的行为。

至多我得到的是引用常量(或将其转换为任何指针类型)是 UB,但没有说一个变量与来自的值相等nullptr.

我想清楚地将 nullptr 常量与一个指针变量分开,指针变量的值等于它。但解决这两种情况的答案是理想的。

我确实意识到,当与 nullptr 等进行比较时,优化可以快速进行,并且可能会基于此简单地删除代码。

如果结论是,如果ptr等于nullptr解引用的值肯定是UB,那么另一个问题是:

Do C and C++ standards imply that a special value in the address space must exist solely to represent the value of null pointers?

最佳答案

当您引用 C 时,取消引用空指针显然是此标准引用(强调我的)中的未定义行为:

(C11, 6.5.3.2p4) "If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.102)"

102): "Among the invalid values for dereferencing a pointer by the unary * operator are a null pointer, an address inappropriately aligned for the type of object pointed to, and the address of an object after the end of its lifetime."

在 C99 中完全相同的引用,在 C89/C90 中类似。

关于c++ - 取消引用一个等于 nullptr 的指针是标准未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28573215/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com