【发布时间】: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:对指针的引用看起来不错,因为他想初始化传入的指针。对于初学者来说,
*&肯定比**更容易理解和使用。 -
Tree::findKey 应该只使用 currentRoot,而不是 root。
标签: c++ g++ binary-search-tree