2012-07-22 151 views
2

我特別提到的代碼函數是getCount()。還有其他一些功能,我沒有包括在這裏(比如找到這個二叉樹的高度和總節點數),它們工作得很好,結果正確。另一方面getCount()會產生除第一個節點(樹的頂部,第一個節點)之外的分段故障。有任何想法嗎?這個C++代碼爲什麼會產生分段錯誤?

#include <string> 
#include <algorithm> 
#include <iostream> 

class Word { 
    public: 
     std::string keyval; 
     long long count; 
     Word() { 
      keyval = ""; 
      count = 0; 
     } 
     Word(std::string S) { 
      keyval = S; 
      count = 1; 
     } 
}; 

class WordBST { 
    public: 
     Word node; 
     WordBST* left_child; 
     WordBST* right_child; 
     WordBST(std::string key);   
     void add(std::string key){ 
      if (key == node.keyval){ 
       node.count++; 
      } 
      else if (key < node.keyval){ 
       if (left_child == NULL){ 
        left_child = new WordBST(key); 
       }else { 
        left_child->add(key); 
       } 
      }else { 
       if (right_child == NULL){ 
        right_child = new WordBST(key); 
       }else { 
        right_child->add(key); 
       } 
      } 
     } 
     long long getCount(std::string key){ 
      if (key == node.keyval){ 
       return (node.count); 
      } 
      else if (key < node.keyval){ 
       left_child->getCount(key); 
      }else if(key > node.keyval){ 
       right_child->getCount(key); 
      }else return 0; 
      /*else { 
       if (key < node.keyval){ 
        left_child->getCount(key); 
       }else{ 
        right_child->getCount(key); 
       } 
      }*/ 
     } 
}; 

WordBST::WordBST(std::string key) { 
    node = Word(key); 
    left_child = NULL; 
    right_child = NULL; 
} 
+3

您是否嘗試過使用調試器? – 2012-07-22 00:58:49

+0

當您第一次解除引用時,是否有'left_child'和'right_child'有效指針? – Aesthete 2012-07-22 00:59:19

回答

2

這是因爲你讓你的代碼在沒有返回語句的情況下運行結束。

long long getCount(std::string key){ 
    if (key == node.keyval){ 
     return (node.count); 
    } else if (left_child && key < node.keyval){ 
     return left_child->getCount(key); // Added return 
    } else if(right_child && key > node.keyval){ 
     return right_child->getCount(key); // Added return 
    } 
    return 0; 
} 

您還需要在整個代碼中的多個位置添加空檢查。你的add方法有他們,但你的getCount沒有。

+0

getCount不返回值與分段錯誤有什麼關係? – Aesthete 2012-07-22 01:03:13

+1

@Aesthete根據C++規範,從聲明爲返回值的函數中返回值不是未定義的行爲。 – dasblinkenlight 2012-07-22 01:04:38

+0

@dasblinkenlight簡短而甜蜜的解決方案。這非常奏效。謝謝。我想知道,沒有返回聲明實際發生了什麼?哦,是的,你說得對,我現在要實施空檢查。 – 2012-07-22 01:05:14

1

在調用方法之前,您不檢查節點的子節點是否存在。

2

我想你應該寫getCount將()這樣的:

long long getCount(std::string key){ 
    if (key == node.keyval){ 
     return (node.count); 
    } 
    else if (key < node.keyval && left_child != NULL){ 
     return left_child->getCount(key); 
    }else if(key > node.keyval && right_child != NULL){ 
     return right_child->getCount(key); 
    }else return 0; 
} 
+0

是的,我已經實施了空檢查。 – 2012-07-22 01:20:33

相關問題