Can C++ array end at memory boundary?

前端 未结 3 2087
谎友^
谎友^ 2021-02-12 00:38

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 all

3条回答
  •  执笔经年
    2021-02-12 00:47

    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.

提交回复
热议问题