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

时间:2018-02-25 19:05:47

标签: 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;
                    }
                }
            }
        }
    }
}

给出输出

Populating tree 0
Setting tree pointer
Moving on to right node...
Segmentation fault (core dumped)

1 个答案:

答案 0 :(得分:9)

因为它没有初始化。

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

在gcc中使用-Wall等警告选项有助于避免这些错误,因为您会收到有关此类问题的通知。

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