Can C++ array end at memory boundary?

前端 未结 3 2088
谎友^
谎友^ 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 01:04

    You're half right. Suppose a hypothetical implementation uses linearly addressed memory and pointers that are represented as 16-bit unsigned integers. Suppose also that the null pointer is represented as zero. And finally, suppose you ask to for 16 bytes of memory, with char *p = malloc(16);. Then it's guaranteed that you will get a pointer of which the numeric value is less than 65520. The value 65520 itself wouldn't be valid, because as you rightly point out, assuming the allocation succeeded, p + 16 is a valid pointer that must not be a null pointer.

    However, suppose now that a hypothetical implementation uses linearly addressed memory and pointers that are represented as 32-bit unsigned integers, but only has an address space of 16 bits. Suppose also again that the null pointer is represented as zero. And finally, suppose again that you ask for 16 bytes of memory, with char *p = malloc(16);. Then it's only guaranteed that you will get a pointer of which the numeric value is less than or equal to 65520. The value 65520 itself would be valid, so long as the implementation makes sure that adding 16 to that gives you the value 65536, and that subtracting 16 gets you back to 65520. This is valid even if no memory (physical or virtual) exists at all at address 65536.

提交回复
热议问题