首页 > 解决方案 > 未检测到空指针

问题描述

我是 C++ 新手。我希望两个不指向任何内容的指针被检测为空指针。然而,这只适用于其中之一。这些指针的物理地址有些不同 - 0xe00000001 vs 0x0(这个被正确检测为空指针)。

我编写了以下代码片段:

#include <iostream>
using namespace std;

struct TNode {
    TNode* Parent;  // Pointer to the parent node
    TNode* Left;  // Pointer to the left child node
    TNode* Right;  // Pointer to the right child node
    int Key;  // Some data
};

int main() {
    TNode parent;
    parent.Key = 2;
    TNode first;
    first.Key = 1;
    first.Parent = &parent;
    parent.Left = &first;
    cout << first.Left << endl; // get 0xe00000001 here
    cout << first.Right <<endl; // get 0x0

    if (first.Right == nullptr) {
        cout <<"rnull"<<endl; // rnull
    }
    if (first.Left == nullptr) {
        cout <<"lnull"<<endl; // nothing
    }

   return 0;
}

这里发生了什么?基本上,我想找到一种方法来检查 first.Left 是否指向任何内容。

标签: c++

解决方案


在您的示例中,first.Left并且first.Right未初始化,为空。这意味着它们基本上包含在分配它们时堆栈上的任何垃圾。访问实际值(例如,通过打印指针)实际上是未定义的行为,但是对于大多数低优化设置的编译器,它只会打印那些垃圾。

解决方案1:为成员变量赋予默认值

如果您希望它们为空,您可以修改TNode以保证它们的初始值为空:

struct TNode {
    TNode* Parent = nullptr;
    TNode* Left = nullptr;
    TNode* Right = nullptr; 
    int Key = 0;
};

int main() {
    TNode n; //Everything initialized to null or 0
}

这将保证它们为空。

解决方案2:定义TNode()初始化成员

或者,您也可以显式定义构造函数,以便它使所有内容为空

struct TNode {
    TNode* Parent, Left, Right;
    // Everything gets default-initialized to null
    TNode() : Parent(), Left(), Right() {}
};

int main() {
    Tnode n; // Everything initialized to nullptr or 0
}

解决方案3:在使用点默认初始化

即使您没有显式定义构造函数,当您{}在声明变量时通过 put 显式初始化它时,所有内容都会初始化为 0(或 null,如果它是指针)。

struct TNode {
    TNode* Parent, Left, Right;
    int Key;
};

int main() {

    TNode iAmUninitialized; // This one is uninitialized

    Tnode iAmInitialized{}; //This one has all it's members initialized to 0
}

推荐阅读