Can C++ array end at memory boundary?

前端 未结 3 2089
谎友^
谎友^ 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:54

    There's an interesting passage at §3.9.2/3 [Compound types]:

    The type of a pointer to void or a pointer to an object type is called an object pointer type. [...] A valid value of an object pointer type represents either the address of a byte in memory (1.7) or a null pointer (4.10).

    Together with the text at §5.7/5 [Additive operators]:

    [...] Moreover, if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object.

    it seems that an array ending at the last byte in memory can not be allocated, if there is a requirement that the one-past-the-end pointer must be valid. If the one-past-the-end pointer is allowed to be invalid, I don't know the answer.

    The section §3.7.4.2/4 [Deallocation functions] states that:

    The effect of using an invalid pointer value (including passing it to a deallocation function) is undefined.

    Thus if comparing a one-past-the-end pointer for an allocated array must be supported, the one-past-the-end pointer must be valid.

    Based on the comments I got, I assume that an implementation can allocate an array without having to care about if the array's one-past-the-end pointer is usable or not. However I would like to find out the relevant passages in the standard for this.

提交回复
热议问题