问题描述
显然,取消引用无效指针会导致未定义的行为.但是如果简单地在一个指针变量中存储一个无效的内存地址呢?
Obviously, dereferencing an invalid pointer causes undefined behavior. But what about simply storing an invalid memory address in a pointer variable?
考虑以下代码:
const char* str = "abcdef";
const char* begin = str;
if (begin - 1 < str) { /* ... do something ... */ }
表达式 begin - 1
计算为无效的内存地址.请注意,我们实际上并没有取消引用这个地址——我们只是在指针运算中使用它来测试它是否有效.尽管如此,我们仍然需要将无效的内存地址加载到寄存器中.
The expression begin - 1
evaluates to an invalid memory address. Note that we don't actually dereference this address - we simply use it in pointer arithmetic to test if it is valid. Nonetheless, we still have to load an invalid memory address into a register.
那么,这是未定义的行为吗?我从没想过是这样,因为很多指针算法似乎都依赖于这种东西,而指针实际上只是一个整数.但是最近我听说即使将无效指针加载到寄存器中的行为也是未定义的行为,因为某些架构会自动抛出总线错误或如果你这样做的话.任何人都可以指出 C 或 C++ 标准的相关部分,这两种方式都可以解决这个问题吗?
So, is this undefined behavior? I never thought it was, since a lot of pointer arithmetic seems to rely on this sort of thing, and a pointer is really nothing but an integer anyway. But recently I heard that even the act of loading an invalid pointer into a register is undefined behavior, since certain architectures will automatically throw a bus error or something if you do that. Can anyone point me to the relevant part of the C or C++ standard which settles this either way?
推荐答案
我这里有 C 草案标准,它被遗漏了.它定义了 ptr + I
在 6.5.6/8 for
I have the C Draft Standard here, and it makes it undefined by omission. It defines the case of ptr + I
at 6.5.6/8 for
- 如果指针操作数指向数组对象的一个元素,并且数组足够大,则结果指向一个元素与原始元素的偏移量,使得结果和原始数组元素的下标之差等于整数表达式.
- 此外,如果表达式 P 指向数组对象的最后一个元素,则表达式 (P)+1 指向数组对象最后一个元素的后面,如果表达式 Q 指向数组对象的最后一个元素后面的一个数组对象,表达式 (Q)-1 指向数组对象的最后一个元素.
您的情况不适合其中任何一个.您的数组也不足以让 -1
调整指针以指向不同的数组元素,也没有任何结果或原始指针指向过去的一端.
Your case does not fit any of these. Neither is your array large enough to have -1
adjust the pointer to point to a different array element, nor does any of the result or original pointer point one-past-end.
这篇关于是否自动存储无效指针未定义行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!