使用 cout 访问对象成员会导致段错误

Accessing objects member with cout causes segfault

本文关键字:段错误 错误 访问 cout 对象 成员 使用      更新时间:2023-10-16

我正在尝试创建一个用于练习的二叉搜索树。 我已经在底部向此树中添加了一些节点,但是当我想通过主函数中的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;
}

第一个明显的错误是BinarySearchTree构造函数中的错误:

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

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