Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C++ array end at memory boundary?

Tags:

c++

arrays

c

c++11

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. It's actually false, and an array might end at memory boundary, OR
  2. It is mandated by C++ standard to end at least one element's worth of memory before the boundary, OR
  3. Neither 1, nor 2, but it is still like that in actual compilers because it makes implementation easier.

Is anything different for the case of C?

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)

like image 725
abi Avatar asked Oct 17 '14 07:10

abi


1 Answers

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.)

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

like image 184
James Kanze Avatar answered Oct 09 '22 01:10

James Kanze