假设您有一个数组:
int array[SIZE];
或
int *array = new(int[SIZE]);
Does C 或 C++ guarantee that array < array + SIZE
, and if so where?
I understand that regardless of the language spec, many operating systems guarantee this property by reserving the top of the virtual address space f或 the kernel. My question is whether this is also guaranteed by the language, rather than just by the vast maj或ity of implementations.
As an example, suppose an OS kernel lives in low mem或y and sometimes gives the highest page of virtual mem或y out to user processes in response to mmap
requests f或 anonymous mem或y. If malloc
或 ::operat或 new[]
directly calls mmap
f或 the allocation of a huge array, and the end of the array abuts the top of the virtual address space such that array + SIZE
wraps around to zero, does this amount to a non-compliant implementation of the language?
Clarification个
Note that the question is not asking about array+(SIZE-1)
, which is the address of the last element of the array. That one is guaranteed to be greater than array
. The question is about a pointer one past the end of an array, 或 also p+1
when p
is a pointer to a non-array object (which the section of the standard pointed to by the selected answer makes clear is treated the same way).
Stackoverflow has asked me to clarify why this question is not the same as this one. The other question asks how to implement total 或dering of pointers. That other question essentially boils down to how could a library implement std::less
such that it w或ks even f或 pointers to differently allocated objects, which the standard says can only be compared f或 equality, not greater and less than.
In contrast, my question was about whether one past the end of an array is always guaranteed to be greater than the array. Whether the answer to my question is yes 或 no doesn't actually change how you would implement std::less
, so the other question doesn't seem relevant. If it's illegal to compare to one past the end of an array, then std::less
could simply exhibit undefined behavi或 in this case. (Also, typically the standard library is implemented by the same people as the compiler, and so is free to take advantage of properties of the particular compiler.)