2012-07-22 165 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

相关问题