假设您有一个数组:

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.)

推荐答案

对来自第6.5.8 para 5节.

如果表达式P指向数组对象的元素

表达式array是P.表达式array + SIZE - 1指向array的最后一个元素,即Q. 因此:

array + SIZE = array + SIZE - 1 + 1 = Q + 1 > P = array

C++相关问答推荐

POSIX文件描述符位置

ATTiny1606定时器TCA 0中断未触发

getchar读css + z还是返回css?

*p[num]和(*p)num的区别

无法用C++编译我的单元测试

在C++中通过空指针隐式访问常量变量的值

平均程序编译,但结果不好

正数之和是负数

为什么realloc函数在此代码中修改变量?

Fprintf正在写入多个 struct 成员,并且数据过剩

为什么WcrTomb只支持ASCII?

带有数组指针的 struct 在print_stack()函数中打印随机数

将复合文字数组用作临时字符串缓冲区是否合理?

传递给函数的 struct 中的数组

为什么 Linux 共享库 .so 在内存中可能比在磁盘上大?

是否可以在多字 C 类型中的任何位置混合存储和类型限定符?

如何向 execl 创建的后台程序提供输入?

定义 int a = 0, b = a++, c = a++;在 C 中定义了行为吗?

strlen 可以是[[未排序]]吗?

c 函数指针,另一种语法