gpt4 book ai didi

c++ - 使用 nullptr 计算指针偏移是否安全?

转载 作者:太空狗 更新时间:2023-10-29 23:33:01 25 4
gpt4 key购买 nike

假设我有两个指针:

char* p1 = nullptr;
char* p2 = std::malloc( 4 );
std::size_t offset = p2 - p1;

以这种方式抵消安全吗?到目前为止,它在我的电脑上运行良好。但是我想知道偏移量是否可以超过 size_t 的最大数量,从而导致此方法失败?

最佳答案

这是未定义的行为,来自 draft C++ standard 5.7 加法运算符:

When two pointers to elements of the same array object are subtracted, the result is the difference of the subscripts of the two array elements. The type of the result is an implementation-defined signed integral type; this type shall be the same type that is defined as std::ptrdiff_t in the header (18.2). [...] Unless both pointers point to elements of the same array object, or one past the last element of the array object, the behavior is undefined.82

另外如引用文献所述,结果是 std::ptrdiff_t 而不是 size_t

另一方面,您可以添加或减去 0 段中的值 7:

If the value 0 is added to or subtracted from a pointer value, the result compares equal to the original pointer value. If two pointers point to the same object or both point one past the end of the same array or both are null, and the two pointers are subtracted, the result compares equal to the value 0 converted to the type std::ptrdiff_t.

如果你想将指针转换为整数值,那么你应该使用 intptr_t or uinitptr_t :

intptr_t   integer type capable of holding a pointer
uintptr_t unsigned integer type capable of holding a pointer

例如:

uintptr_t ip = reinterpret_cast<uintptr_t>( p2 ) ;

关于c++ - 使用 nullptr 计算指针偏移是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24889947/

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