C ++阵列可以结束在内存界? [英] Can C++ array end at memory boundary?

查看:118
本文介绍了C ++阵列可以结束在内存界?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++标准(和C为此事)允许创建(未解除引用虽然)的指针将一个元件过去数组的末尾。这是否意味着数组决不会在这样一个位置,它的最后一个元素的内存边界结束分配呢?据我所知,在实践中部分/全部实现可能遵守这个约定,但哪一个符合下列条件:

C++ standard (and C for that matter) allows to create (not dereference though) a pointer to one element past the end of the array. Does this mean that an array will never be allocated at such a location that its last element ends at the memory boundary? I understand that in practice some/all implementation might follow this convention, but which one the following is true:


  1. 它实际上是假的,一个阵列可以在存储边界结束,或者

  2. 这是由C ++标准规定的边界之前结束的内存至少有一个元素的价值或

  3. 无论是1,2也没有,但它仍然像在实际的编译器,因为它使实现更容易。

时有什么不同的C的情况下?

Is anything different for the case of C?

更新:
它看起来像 1 是正确的答案。答案见詹姆斯甘孜以下,也见 efence表示 HTTP:/ /linux.die.net/man/3/efence - 感谢迈克尔·查斯顿为指针吧)

Update: It seems like 1 is the correct answer. See answer from James Kanze below, and also see efence (http://linux.die.net/man/3/efence - thanks to Michael Chastain for the pointer to it)

推荐答案

这是实现必须允许一个指向一个过去的结束
存在。它是如何做到这一点是它的业务。在许多机器上,你
可以放心地把任何值转换成一个指针,没有风险(除非
取消引用它);在这样的系统中,一个过去的结束
指针可能指向映射的内存—我有
Windows其中它确实在实际遇到的情况。

An implementation must allow a pointer to one past the end to exist. How it does this is its business. On many machines, you can safely put any value into a pointer, without risk (unless you dereference it); on such systems, the one past the end pointer may point to unmapped memory—I've actually encountered a case under Windows where it did.

在其它机器上,只装载一个指向映射的内存
到寄存器将陷阱,导致程序崩溃。上
这样的机器,实现必须确保这种情况不会
发生,或者通过拒绝使用的最后一个字节或字
分配的内存,或者通过确保所有使用指针
比提领它避免了其他可能的任何指示
使得硬件把它当作一个无效的指针。 (大多数这样的
系统有独立的地址和数据寄存器,并且将只
陷阱如果指针被加载到地址寄存器。如果
数据寄存器是足够大时,编译器可以安全地装载
指针成例如一个数据寄存器比较。这是
常常需要反正作为地址寄存器总是不
支持比较)。

On other machines, just loading a pointer to unmapped memory into a register will trap, causing the program to crash. On such machines, the implementation must ensure that this doesn't happen, either by refusing to use the last byte or word of allocated memory, or by ensuring that all use of the pointer other than dereferencing it avoids any instructions which might cause the hardware to treat it as an invalid pointer. (Most such systems have separate address and data registers, and will only trap if the pointer is loaded into an address register. If the data registers are large enough, the compiler can safely load the pointer into a data register for e.g. comparison. This is often necessary anyway, as the address registers don't always support comparison.)

回复你最后一个问题:C和C ++在这方面是完全一致; C ++简单地接管从C的规则。

Re your last question: C and C++ are exactly identical in this respect; C++ simply took over the rules from C.

这篇关于C ++阵列可以结束在内存界?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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