2017-01-14 59 views
-2

我正在嘗試爲練習創建一個二叉搜索樹。我在這個樹底部添加了一些節點,但是當我想通過主函數的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; 
} 
+0

問題沒有轉載。您能否提供更多元素作爲顯示SegFault的調試器輸出?我的輸出是「'第一\ n 第二\ n 第一\ n 第三\ n bst.root->數據是15 \ n bst.root->右是1c833a0 \ n bst.root->左側是1c83380'「 –

回答

0

第一個明顯的錯誤是這樣在你的BinarySearchTree構造:

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

root是未初始化的,所以它包含任何垃圾值。然後,當您使用該垃圾值(root->data)時,您的程序已進入未定義行爲的土地。

+0

在閱讀您的評論後,我決定將'Node * root;'更改爲'Node * root = new Node();'。我知道我們應該儘量減少使用新關鍵字。這似乎並不像我們必須使用堆的情況。如何在仍然使用堆棧的時候初始化這個? – theBigDream

+0

我的評論只是說你正在使用未初始化的指針。在嘗試解引用或使用它們之前,所有指針必須指向某個有效的地方。除非你用'root'來代替指針,否則你別無選擇,只能動態地分配一個 – PaulMcKenzie

相關問題