显然,取消引用无效指针会导致未定义的行为.但是如果简单地在一个指针变量中存储一个无效的内存地址呢?
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
您的情况不适合其中任何一个.您的数组也不足以让 -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.
这篇关于是否自动存储无效指针未定义行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!