取消引用无效的指针但不使用结果是C ++中的未定义行为吗? [英] Is it undefined behavior in C++ to dereference an invalid pointer but not use the result?
问题描述
请考虑以下C ++代码:
Consider the following piece of C++ code:
int main() {
int* ptr; // Deliberately uninitialized
(void) *ptr; // Dereference, do not use result
}
此代码是否导致未定义的行为?我假定答案是是",即使*ptr
的值实际上没有在任何地方使用.规范中是否有特定部分可以保证这一点?
Does this code result in undefined behavior? I assume that the answer is "yes" even though the value of *ptr
is not actually used anywhere. Is there a particular part of the spec that guarantees this?
(对于这是重复的邮件,我深表歉意,但似乎无法在网站上找到其他任何专门询问此问题的内容.)
(I apologize if this is a duplicate, but I can't seem to find anything else on the site that specifically asks this question.)
推荐答案
仅取消引用尚未分配或标记为只读的指针会导致CPUs
中的硬件异常内存管理单元.因此,即使您不使用通过解引用包含随机值的指针而不会返回的垃圾值,也无法保证CPU
将从此类事件中返回.
Simply dereferencing a pointer that has not been allocated or is marked as read-only can cause a hardware exception in the CPUs
memory management unit. So even if you don't use whatever garbage value would be returned by dereferencing a pointer that contains a random value, there is no guarantee the CPU
would return from such an event.
但是,根据ISO C++11 Standard
,声明为未初始化的指针必须具有奇异值.因此,未初始化的指针的值不是 undefined ,因为它不是垃圾.
However, according to the ISO C++11 Standard
a pointer that is declared uninitialized must have a singular value. So the value of an uninitialized pointer is not undefined as in it is not garbage.
然而,标准指出,对于此类奇异值指针的大多数操作均未定义,只是用非奇异值覆盖奇异值 :
However the Standard states that most operations on such a singular value pointer are undefined with the exception of overwriting the singular value with a non singular value:
24.2.1 通常是 [ iterator.requirements.general ]
24.2.1 In general [ iterator.requirements.general ]
5 []示例:在声明未初始化的指针x之后(与int * x;一样),必须始终假定x具有奇异值指针的值. —结束示例] 对于单数,大多数表达式的结果均未定义;唯一的例外是销毁具有奇异值的迭代器,将非奇异值分配给具有奇异值的迭代器,对于满足DefaultConstructible要求的迭代器,请使用值初始化的迭代器作为复制或移动操作. []注意:默认区别不提供此保证,尽管区别仅适用于琐碎的默认构造函数的类型,例如指针或持有指针的集合. —尾注 ] 在这种情况下,奇异值与任何其他值一样被覆盖.可引用的值总是非奇数.
5 [ Example: After the declaration of an uninitialized pointer x (as with int* x;), x must always be assumed to have a singular value of a pointer. — end example ] Results of most expressions are undefined for singular values; the only exceptions are destroying an iterator that holds a singular value, the assignment of a non-singular value to an iterator that holds a singular value, and, for iterators that satisfy the DefaultConstructible requirements, using a value-initialized iterator as the source of a copy or move operation. [ Note: This guarantee is not offered for default initialization, although the distinction only matters for types with trivial default constructors such as pointers or aggregates holding pointers. — end note ] In these cases the singular value is overwritten the same way as any other value. Dereferenceable values are always non-singular.
这篇关于取消引用无效的指针但不使用结果是C ++中的未定义行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!