我正在嘗試爲練習創建一個二叉搜索樹。我在這個樹底部添加了一些節點,但是當我想通過主函數的cout檢查這些節點及其成員時,我得到了一個segFault錯誤。然而奇怪的是,我可以分配這些成員,但我沒有收到這個問題。
如果任何人都可以幫助我理解爲什麼cout會導致這種情況,那將是不勝感激。謝謝。使用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;
}
問題沒有轉載。您能否提供更多元素作爲顯示SegFault的調試器輸出?我的輸出是「'第一\ n 第二\ n 第一\ n 第三\ n bst.root->數據是15 \ n bst.root->右是1c833a0 \ n bst.root->左側是1c83380'「 –