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:
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With