它是不确定的行为,形成从堆栈地址的指针范围是多少? [英] Is it undefined behavior to form a pointer range from a stack address?

查看:385
本文介绍了它是不确定的行为,形成从堆栈地址的指针范围是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一些C或C ++程序员都惊讶地发现,即使<一个href=\"http://stackoverflow.com/questions/3838855/is-storing-an-invalid-pointer-automatically-undefined-behavior\">storing无效的指针是不确定的行为。但是,对于堆或叠阵,没关系的一个地址存储过去阵列,它允许你存储在循环使用的终点位置的结束。

Some C or C++ programmers are surprised to find out that even storing an invalid pointer is undefined behavior. However, for heap or stack arrays, it's okay to store the address of one past the end of the array, which allows you to store "end" positions for use in loops.

但它是不确定的行为,形成从单一堆栈变量的指针范围,如:

But is it undefined behavior to form a pointer range from a single stack variable, like:

char c = 'X';
char* begin = &c;
char* end = begin + 1;

for (; begin != end; ++begin) { /* do something */ }

虽然上面的例子是pretty没用的,这可能是因为有些功能需要一个指向范围内的情况下非常有用,你有,你只是有一个值传递给它的情况。

Although the above example is pretty useless, this might be useful in the event that some function expects a pointer range, and you have a case where you simply have a single value to pass it.

这是不确定的行为?

推荐答案

这是允许的,其行为是指两者开始结束安全源性指针值

This is allowed, the behavior is defined and both begin and end are safely-derived pointer values.

在C ++标准第5.7节( [expr.add] )第4段:

In the C++ standard section 5.7 ([expr.add]) paragraph 4:

:用于这些操作符的目的,一个指向非数组对象的行为相同的指针长度的一个的阵列与对象作为其元素类型的类型的第一元件。

在使用C的类似条款可以在该C99 / N1256标准部分找到6.5.6条第7款。

When using C a similar clause can be found in the the C99/N1256 standard section 6.5.6 paragraph 7.

:用于这些操作符的目的,一个指向的对象是不是一个数组中的一个元素的行为相同的指针长度的一个阵列与对象为一体的类型的第一元件其元素的类型。

顺便说一句,在第3.7.4.3( [basic.stc.dynamic.safety] )安全源性指针有一个注脚:


As an aside, in section 3.7.4.3 ([basic.stc.dynamic.safety]) "Safely-derived pointers" there is a footnote:

本节不上取消引用指针的内存不受 ::分配新的运营商施加限制。这保留了许多C ++实现使用其他语言编写的二进制库和组件的能力。特别是,这仅针对C二进制代码,因为访问指向由的malloc 分配的内存没有限制。

This section does not impose restrictions on dereferencing pointers to memory not allocated by ::operator new. This maintains the ability of many C++ implementations to use binary libraries and components written in other languages. In particular, this applies to C binaries, because dereferencing pointers to memory allocated by malloc is not restricted.

这表明,在整个堆栈指针算法是实现定义的行为,而不是不确定的行为。

This suggests that pointer arithmetic throughout the stack is implementation-defined behavior, not undefined behavior.

这篇关于它是不确定的行为,形成从堆栈地址的指针范围是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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