gpt4 book ai didi

C++ 最大有效内存地址

转载 作者:可可西里 更新时间:2023-11-01 15:18:22 25 4
gpt4 key购买 nike

我经常看到添加一个值的代码,比如一个指针的长度,然后使用这个值,例如

T* end = buffer + bufferLen;//T* + size_t

if (p < end)

但是,缓冲区是否有可能被分配到足够靠近内存末尾的位置,以至于“buffer + bufferLen”可能溢出(例如 0xFFFFFFF0 + 0x10),导致“p < end”为假,即使 p 是一个有效的元素地址(例如 0xFFFFFFF8)。

如果可能的话,当我看到很多东西都在开始/结束范围内工作时,如何避免在最后一个元素之后结束下一个元素

最佳答案

来自标准:

5.9 Relational operators [expr.rel]

If two pointers point to elements of the same array or one beyond the end of the array, the pointer to the object with the higher subscript compares higher.

所以你不用担心;一致的实现将确保尾后指针与数组的其余部分进行正确比较。此外,

3.7.4.1 Allocation functions [basic.stc.dynamic.allocation]

[...] The pointer returned shall be suitably aligned so that it can be converted to a pointer of any complete object type with a fundamental alignment requirement (3.11) and then used to access the object or array in the storage allocated [...]

这意味着返回的指针应该能够被视为指向适当大小的数组开头的指针,因此 5.9 继续成立。如果分配函数调用是调用 operator new[] (5.3.4:5) 的结果,就会出现这种情况。

作为一个实际问题,如果你在一个可以想象分配器(不一致地)返回以 0xFFFFFFFF 结尾的内存块的平台上,你在大多数情况下可以写

if (p != end)

关于C++ 最大有效内存地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12038084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com