【问题标题】:BST keep getting Segmentation faultBST 不断收到分段错误
【发布时间】:2011-04-27 13:09:10
【问题描述】:

编辑:通过 gdb 运行它会给出

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400e4c in Tree::findKey(std::basic_string<char, std::char_traits<char>, std::allocator<char> >&, int, Tree::Node*) ()

我的第一个 BST 代码需要一些帮助,我不断收到分段错误,我认为这是内存泄漏?如果是这样,我不知道在哪里/如何修复是我认为导致问题的代码。是不是因为我还没有设置复制构造函数??

tree.cpp 文件

Tree::Tree()
{
  root = NULL;
}

bool Tree::insert(int k, string s)
{
  return insert(root, k, s);
}
//HELPER Call find data with key function
bool Tree::findKey(string& s, int k)
{
    return findKey(s, k, root);
}
bool Tree::insert(Node*& currentRoot, int k, string s)
{
  if(currentRoot == NULL){
    currentRoot = new Node;
    currentRoot->key = k;
    currentRoot->data = s;
    currentRoot->left = NULL;
    currentRoot->right = NULL;
    return true;
  }
  else if (currentRoot->key == k)
    return false;
  else if (currentRoot->key > k)
    return insert(currentRoot->left, k, s);
  else
    return insert (currentRoot->right,k, s);
}
bool Tree::findKey(string& s, int k, Node* currentRoot)
{
    if (currentRoot->key == k){
        s = root->data;
        return true;
    }
    else if (root->key < k)
        return findKey (s, k, root->right);
    else if (root->key > k)
        return findKey (s, k, root->left);
    else
        return false;
}

main.cpp

int main()
{
string sout;
  Tree test;
    test.insert(1, "a");
    test.insert(2, "b");
    test.insert(3, "c");
    test.findKey(sout, 3);
    cout<<sout<<endl;
  return 0;
}

【问题讨论】:

  • 您是否使用 'valgrind' 找到了您的实现遇到 seg 错误的地方?
  • 如何在调试器或 IDE 中运行它,以便告诉我们它在哪一行出现段错误?
  • 您真的要传递对指针的引用吗? bool Tree::insert(Node*& currentRoot, int k, string s)
  • @tgmath:对指针的引用看起来不错,因为他想初始化传入的指针。对于初学者来说,*&amp; 肯定比** 更容易理解和使用。
  • Tree::findKey 应该只使用 currentRoot,而不是 root。

标签: c++ g++ binary-search-tree


【解决方案1】:
bool Tree::findKey(string& s, int k, Node* currentRoot)
{
    if (currentRoot->key == k){
        s = root->data;
        return true;
    }
    else if (root->key < k)
        return findKey (s, k, root->right);
    else if (root->key > k)
        return findKey (s, k, root->left);
    else
        return false;
}

你总是使用root 而不是currentRoot,所以你不会真的从树上下来,并且会在某个时候得到一个stackoverflow。此外,您还没有检查currentRoot 是否为NULL,因为如果您访问它,您将得到一个很好的段错误(这就是@tgmath 的意思)。

bool Tree::findKey(string& s, int k, Node* currentRoot)
{
    if(currentRoot == NULL)
        return false;
    // as before ...
}

【讨论】:

    【解决方案2】:

    当我查看您的方法时,我发现了一些可能的段错误。 想想边缘情况吧。

    这里发生了什么?:

    Tree test; 
    test.findKey(sout, 3);
    

    Tree test;
    test.insert(1, "a");
    test.findKey(sout, 3);
    

    解决这些情况并继续。

    【讨论】:

    • 你能帮我把它弄小一点吗??我真的不明白你的意思。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多