考虑一个不是nullptr
的指针char* p
,以及循环
while(++p);
行为是明确定义的还是未定义的?换句话说,当达到最大可分配内存(可能是 2^32 或 2^64)时,指针最终会变为 0 还是这只是 UB?
std::numeric_limits是(如预期的那样)不专门用于指针类型。
最佳答案
简短回答:根据规范,这是未定义的行为。执行任何导致未分配内存超过已分配项目一个地址的指针算法(请参阅 GCC 文档中的 One Past the End 章节以了解其重要性)是未定义的行为。
要了解原因,让我们看看标准:
C++11 标准中的第 3.7.4.3.2 节枚举了所有“安全派生指针”类型。该标准第 3.7.4.3.2 节中的大多数项目描述了合法获取对象引用的方法。假设一个指针指向分配的内存,3.7.4.3.2 简单地声明:
A pointer value is a safely-derived pointer to a dynamic object only if it has an object pointer type and it is one of the following:
- the result of well-defined pointer arithmetic (5.7) using a safely-derived pointer value;
第 5.7.4 节指出:
For the purposes of these operators, a pointer to a nonarray object behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.
最后,第 5.7.5 节:
If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.
关于c++ - 指针类型环绕它们的最大值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30089415/