簡體   English   中英

C ++分段錯誤(核心轉儲)

[英]C++ Segmentation error(core dumped)

所以我遇到的問題是分段錯誤。 我正在嘗試實現一個AVLtree,我相信我的代碼的這部分是問題,但我無法確定我做錯了什么。

我的AVLtree類的一部分:

  Node* AVLtree::findNode(string cityID){
       Node *thisNode = this->rootNode;
       while(thisNode!=0){
            if(thisNode->getCity()->getName().compare(cityID)==0){return thisNode;
            }else if(thisNode->getChildR()->getCity()->getName() < cityID){ thisNode = thisNode->getChildR();
            }else{thisNode = thisNode->getChildL();}
       }
  return this->rootNode;
  } 

我的主要檔案:

     int main(){
     ....
     City city1("BoomTown", "EU", 1.01, 2.02); 
     ....
     AVLtree avltree1(&city1);
     cout<< "TEST 1: AVLtree with city paramter of city1 (" << city1.getName()<< ")" << endl;
     cout << "TEST 2: Getting name of city1: " << avltree1.findNode("BoomTown")->getCity()->getName() << endl;

我的City類和Node類都可以工作,我可以創建一個AVLtree。 我似乎無法在其中找到一個節點。

這是我的輸出:

    $ ./mainTest
    TEST 1: AVLtree with city paramter of city1 (BoomTown)
    Segmentation fault (core dumped)

我很抱歉,如果這是一個簡單的錯誤,但我是C ++的新手,需要時間和練習來學習:)提前謝謝。

(ps如果您需要更多代碼,請詢問)

在您的代碼中,您似乎檢查當前節點是否為null,但在訪問之前您不檢查子節點是否為null:

while(thisNode!=0) {
    // ... 
    if(thisNode->getChildR()->getCity()->getName() < cityID){
                 ^^^^^^^^^^^
                 here

問題可能與您沒有檢查您的方法是否返回propper指針有關。 如果您嘗試在無效指針上調用方法,則會產生分段錯誤。

在您的情況下:如果thisNode->getChildR()實際上沒有返回有效指針,則調用getCity()會進行核心轉儲。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM