使用cout访问对象成员会导致segfault

时间:2017-01-14 20:23:22

标签: c++

我正在尝试为练习创建二叉搜索树。我已经向这个树添加了一些节点,但是当我想通过主函数中的cout检查这些节点及其成员时,我得到了一个segFault错误。然而,奇怪的是,我可以指派这些成员,但我没有收到这个问题 如果有人能帮助我理解为什么cout导致这一点,那将非常感激。谢谢。

编辑: 如果在实例化之后我没有更改根值,它会帮助发生这些段错误。

    #include <iostream>

using namespace std;

class Node{
    public:

    Node(){
    }

    Node(int someNum){
        data = someNum;
    }
    int data;
    Node *right;
    Node *left;
};

class BinarySearchTree{
    public:

    Node *root;// = new Node();

    BinarySearchTree(int rootValue);
    void insertNode(Node *aNode, int nodeValue);

};

BinarySearchTree::BinarySearchTree(int rootValue){
    if(root != NULL){

        root->data = rootValue;
        root->left = NULL;
        root->right = NULL;
        }
}

void BinarySearchTree::insertNode(Node *aNode, int nodeValue){
    if(nodeValue<(aNode->data)&&aNode->left==NULL){   //If it's less than and left child doesn't exist
        cout<<"first"<<endl;
        Node *newNode = new Node(nodeValue);         //Create a new node with that value
        aNode->left = newNode;
        }
    else if(nodeValue<(aNode->data)&&aNode->left!=NULL) //If it's less than and left child DOES exist
        {
        cout<<"second"<<endl;
        insertNode(aNode->left, nodeValue);             //Recursively travel to the left
        }
    else if(nodeValue>=(aNode->data)&&aNode->right==NULL){
        cout<<"third"<<endl;
        Node *newNode = new Node(nodeValue);
        aNode->right = newNode;
        }
    else{
        cout<<"fourth"<<endl;
        insertNode(aNode->right, nodeValue);
    }
}

int main()
{
    BinarySearchTree bst(10);
    bst.insertNode(bst.root, 5);
    bst.insertNode(bst.root, 3);
    bst.insertNode(bst.root, 12);
    bst.root->data = 15;            //No segFault

    cout<<"bst.root->data is "<<bst.root->data<<endl;                     //Why does this cause a segFault?  And why does it prevent other stuff from printing out?
    cout<<"bst.root->right is "<<bst.root->right<<endl;     //Why does this cause a segFault?
    cout<<"bst.root->left is "<<bst.root->left<<endl;         //Why does this cause a segFault?

    return 0;
}

1 个答案:

答案 0 :(得分:0)

第一个引人注目的错误是BinarySearchTree构造函数:

 if(root != NULL){
   root->data = rootValue;  // undefined behavior

root未初始化,因此它包含任何垃圾值。然后,当您使用该垃圾值(root->data)时,您的程序已进入未定义行为