为什么超越指针运算未定义的行为? [英] Why is out-of-bounds pointer arithmetic undefined behaviour?

查看:263
本文介绍了为什么超越指针运算未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下示例是来自维基百科的

The following example is from Wikipedia.

int arr[4] = {0, 1, 2, 3};
int* p = arr + 5;  // undefined behavior

如果我从不取消引用p,那么为什么是arr + 5单独的未定义行为?我希望指针表现为整数 - 除非被解引用,指针的值被认为是内存地址。

If I never dereference p, then why is arr + 5 alone undefined behaviour? I expect pointers to behave as integers - with the exception that when dereferenced the value of a pointer is considered as a memory address.

推荐答案

这是因为指针的行为不像整数。

That's because pointers don't behave like integers. It's undefined behavior because the standard says so.

在大多数平台上(如果不是全部),你不会遇到崩溃或遇到可疑的行为,如果你' t解引用数组。但是,如果你不解引用它,那么添加的意义是什么?

On most platforms however (if not all), you won't get a crash or run into dubious behavior if you don't dereference the array. But then, if you don't dereference it, what's the point of doing the addition?

也就是说,技术上100%正确,并保证不会崩溃根据C ++ 11规范的§5.7¶5。但是,该表达式的结果是未指定(只是保证不会溢出);而任何其他超过一个过去数组边界的表达式是显式的未定义行为。

That said, note that an expression going one over the end of an array is technically 100% "correct" and guaranteed not to crash per §5.7 ¶5 of the C++11 spec. However, the result of that expression is unspecified (just guaranteed not to be an overflow); while any other expression going more than one past the array bounds is explicitly undefined behavior.

注意:这并不意味着从一个一个偏移读取和写入是安全的。您可能会 正在编辑不属于该数组的数据,导致状态/内存损坏。你只是不会导致溢出异常。

Note: That does not mean it is safe to read and write from an over-by-one offset. You likely will be editing data that does not belong to that array, and will cause state/memory corruption. You just won't cause an overflow exception.

我的猜测是,这是因为它不仅解除引用的错误。还有指针算术,比较指针等等。所以只是更容易说不要这样做,而不是枚举它可能危险的情况。

My guess is that it's like that because it's not only dereferencing that's wrong. Also pointer arithmetics, comparing pointers, etc. So it's just easier to say don't do this instead of enumerating the situations where it can be dangerous.

这篇关于为什么超越指针运算未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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