我能得到一个指向 nullptr 的指针吗,它有效吗

Can I get a pointer to a pointer pointing to nullptr, is it valid

我对以下代码有一些疑问:

void b(int** a){
        int *c = new int;
        *a = c;
        **a = 120;
}

int main(){
        int *a = nullptr;
        b(&a);
        if(a)
                delete a;
        return 0;
}

我担心这可能会导致 UB,因为它是一个 nullptr,我正在更改指针地址,因为我正在获取对它的引用,但后来我开始认为这不应该成为问题,因为我会有。 一些地址 -> nullptr。这个地址是有效的,所以我可以更改它。

我 运行 这个测试不止一次并且启用了 -fsanitize=address 并且它工作正常。 但是,这是正确的吗?

My concern is that could cause UB, as it is a nullptr

作为 b() 参数的 a 不是 nullptr,它会在取消引用之前分配指向的指针,所以这不是问题。

我不认为你有内存泄漏,但你必须非常小心这样的事情:

#include <iostream>

void b(int** a)
{
  int *c = new int;
  *a = c;
  **a = 120;

  // if C is deleted then the *a needs to be set to nullptr
  //delete c;
  //*a = nullptr;

  // Not needed as this will just be defeferenced off the stack
  // *a and c are two different pointers in memory so this is fine
  c = nullptr;
}

int main(){
  int *a = nullptr;
  std::cout << "Before B, a=" << a << std::endl;
  b(&a);
  std::cout << "After B, a=" << a << std::endl;
  std::cout << "After B, *a=" << *a << std::endl;
  if(a)
  {
    delete a;
  }

  // a still has a pointer with an address and can't be trusted
  std::cout << "End A, a=" << a << std::endl;
  // On repl.it, it prints 0
  std::cout << "End *a, a=" << *a << std::endl;

  return 0;
}