为什么这个指针不是NULL,尽管它从未被初始化?

the*_*cer 1 c++ pointers segmentation-fault

我试图在C++中实现一个简单的二叉树,但指针给我带来了麻烦.尽管我从未为指针分配结构,但它不会计算为NULL,因此,实际上永远不会分配并且一切都会中断.

代码:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

struct BTNode {
    int data;
    BTNode *left;
    BTNode *right;
};

int main() {
    BTNode *tree;
    srand(time(NULL));  

    int input[11]; 
    for(int i=0;i<11;i++) {
        input[i] = 1 + rand()%50;
    }

    for(int i=0;i<11;i++) { //populate binary tree
        cout << "Populating tree " << i << "\n";
        if(!tree) { 
            tree = new BTNode();
            cout << "Initialising tree\n";
            tree->data = input[i];  
        } else {
            cout << "Setting tree pointer\n";
            BTNode *curnode = tree;
            while(true) {
                if(curnode->data >= input[i]) {
                    if(!curnode->left) {
                        curnode->left = new BTNode();
                        curnode->left->data = input[i];
                        cout << "Put " << input[i] << " in left node of " << curnode->data << ".\n";
                        break;
                    }
                    else {
                        cout << "Moving on to left node...\n";
                        curnode = curnode->left;
                    }
                }
                else {
                    if(!curnode->right) {
                        curnode->right = new BTNode();
                        curnode->right->data = input[i];
                        cout << "Put " << input[i] << " in right node of " << curnode->data << ".\n";
                        break;
                    }
                    else {
                        cout << "Moving on to right node...\n";
                        curnode = curnode->right;
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

给出输出

Populating tree 0
Setting tree pointer
Moving on to right node...
Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)

Kon*_*ski 9

因为它没有初始化.

局部变量未初始化为nullptr或等等.它们可以具有任何值*,这几乎意味着 - 始终初始化您的值.

使用-Wallgcc 等警告选项有助于避免这些错误,因为您将被告知此类问题.

*根据规范不完全正确,但是有用的简化.