提问者:小点点

从nullptr中减去指针不会产生预期的值


一些基本的指针数学会导致编译器之间产生不明确的结果。

#include <cstdint>

int main()
{
    int * test = new int{100};
    int * a = nullptr;
    auto diff = test - a;
    int * test_copy = diff + a;
    return *test_copy;
}

https://godbolt.org/z/gvfg1m

  • GCC认为结果是100.
  • Clang认为结果是132.
  • MSVC认为结果也不是100.

共1个答案

匿名用户

这里的问题是指针不指向同一个对象。将运算符+运算符-应用于不属于同一对象的指针是未定义的行为。

测试来自全局运算符NewNullPtr不是全局运算符new管理的内存的一部分。这也是两个分开的东西。

为了测试这一点,不要将a设置为nullptr,而是将其设置为另一个来自全局运算符new的随机int

#include <cstdint>

int main()
{
    int * test = new int{100};
    int * a = new int{};
    auto diff = test - a;
    int * test_copy = diff + a;
    return *test_copy;
}

https://godbolt.org/z/req74S

现在编译器似乎很高兴。