自动存储无效指针未定义的行为? [英] Is storing an invalid pointer automatically undefined behavior?

查看:115
本文介绍了自动存储无效指针未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然,取消引用无效指针会导致不确定的行为。但是,关于什么简单的存储的一个指针变量无效的内存地址?

Obviously, dereferencing an invalid pointer causes undefined behavior. But what about simply storing an invalid memory address in a pointer variable?

考虑以下code:

const char* str = "abcdef";
const char* begin = str;
if (begin - 1 < str) { /* ... do something ... */ }

这位前pression 开始 - 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标准在这里,它使得它不作为未定义的。它定义了

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


  • 如果指针操作数指向数组对象的元素,并且阵列足够大,结果指向一个元件从原始元件偏移,使得所得到的和原始的数组元素的下标之差等于整前pression。

  • 此外,如果前pression p指向数组对象的最后一个元素,前pression(P)+1点中的一个过去的数组对象的最后一个元素,如果前pression Q点中的一个过去的数组对象的最后一个元素,前pression(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.

这篇关于自动存储无效指针未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆