【问题标题】:Why is this pointer not NULL, despite it never being initalised?为什么这个指针不为 NULL,尽管它从未被初始化?
【发布时间】:2018-02-25 19:05:47
【问题描述】:

我试图在 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)

【问题讨论】:

  • 您回答了自己的问题。它没有被初始化。特别是,它还没有被初始化为 NULL。从任何未初始化的变量中读取都是未定义的行为,指针不是特例。

标签: c++ pointers segmentation-fault


【解决方案1】:

因为它没有初始化。

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

在 gcc 中使用警告选项(例如 -Wall)有助于避免这些错误,因为您会被告知此类问题。

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

【讨论】:

  • 你是对的!更改 BTNode *tree 后;到 BTNode *tree = NULL;一切正常。
【解决方案2】:

为指针变量分配的内存空间可能包含垃圾值。因此,当您检查 NULL 时,它们不为空。但它们也不指向节点。这就是为什么你会崩溃。您应该始终初始化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 2013-02-17
    • 2013-09-07
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    相关资源
    最近更新 更多