未检测到的空指针

Null pointer not detected

本文关键字:空指针 检测      更新时间:2023-10-16

我是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.Leftfirst.Right是不可初学的, not null。这意味着它们在分配时基本上包含堆栈上的任何垃圾。访问实际值(例如,通过打印指针(实际上是未定义的行为,但是大多数编译器都在低优化设置上,它将仅打印该垃圾。

解决方案1:给成员变量默认值

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

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()初始化成员

另外,您也可以明确定义构造函数,使其使所有内容变为null

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:在使用点默认initialize

即使您不明确定义构造函数,当您在声明该变量时将{}显式初始化它时,所有内容都会初始化为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
}

首先,在C和C 中,没有一个指向指向的指针。无论指针中的价值如何,它都指向某物。甚至NULL也是一个解决" 0"的指针,但我们使用的指针表示代表零。一个非直接化的指针的问题在于,它可以指向任何事物,并且任何事物都可能是一个非法地址,它会导致例外或指向应用程序中的其他内容,如果修改了数据,则会导致不希望的侧面 - 效力。

在您的情况下,第二个指针为0x00,为空。但是,第一个指针是0x01,这不是null。