用C/C++澄清悬空指针

123*_*234 0 c++ dangling-pointer

关于在C/C++中悬空指针,我有点困惑

void remove(){
Node* curr = new Node(10);
Node* pt = curr;
delete curr;

// do something here
// do other thing here
}
Run Code Online (Sandbox Code Playgroud)

我假设Node* pt在函数remove()终止之前仍然悬空指针?

终止Node* pt后我不必担心指针remove()

Dav*_*rtz 8

你的问题似乎是基于错误的假设,即悬挂指针有问题.它绝对没有任何问题,并且将所有悬空指针设置为等的尝试NULL是反模式.只是不要取消引用悬空指针.

在注释部分remove,但是curr并且pt是悬空指针,因为它们都指向已被删除的对象.只要该代码不会取消引用它们,就没有问题.

  • _您的问题似乎基于错误的假设,即悬空指针有问题_。爱它。+1 (2认同)

kfs*_*one 5

当调用 时delete curr,存储的值curr没有改变,但该位置的内存已返回给系统。

让我们逐行浏览您的代码:

Node* curr = new Node(10);
Run Code Online (Sandbox Code Playgroud)

为了便于讨论,我们假设分配的内存地址为 0x1000,这意味着curr现在的值为0x1000

Node* pt = curr;
Run Code Online (Sandbox Code Playgroud)

pt 现在的值(指向位置)也为 0x1000。

delete curr;
Run Code Online (Sandbox Code Playgroud)

这会将位置 0x1000 处的内存返回给系统。然而,此时两者curr仍然pt包含值 0x1000。

它们都是悬空指针。

当您使用原始指针时,悬空指针是不可避免的,并且它们并不是隐式的坏。您只需小心不要使用悬空指针或返回悬空指针。

void badfunc() {
    char* p = new char[10];
    delete p;
    return p;  // use of dangling pointer
}
Run Code Online (Sandbox Code Playgroud)