【发布时间】:2014-11-05 08:16:40
【问题描述】:
我正在尝试插入二叉搜索树。每当我增加树的大小时,我目前都会收到 SIGSEGV 分段错误错误。我的问题是什么?我该如何解决?提前致谢。
在我的头文件中公开:
bool insert(const Comparable & x)
{
insert(x, root);
}
int size(const Comparable & x)
{
size(x, root);
}
在我的头文件中私有:
private:
struct BinaryNode
{
Comparable key;
BinaryNode *left;
BinaryNode *right;
vector<int> lineNumberList;
int size;
BinaryNode(const Comparable & thekey, BinaryNode *lt, BinaryNode *rt)
: key{ thekey }, left{ lt }, right{ rt } { }
BinaryNode(Comparable && thekey, BinaryNode *lt, BinaryNode *rt)
: key{ move(thekey)}, left{ lt }, right{ rt } { }
};
int size(BinaryNode *t)
{
if (t == NULL)
return 0;
else
return (t->left->size) + 1 + (t->right->size);
}
bool insert(const Comparable & x, BinaryNode *t){
if (t == NULL)
{
root = new BinaryNode{ x, NULL, NULL };
t->size++; **Segmentation fault**
return true;
}
else if (x < t->key)
{
insert(x, t->left);
if (insert(x, t->left)){
t->size++; **Segmentation fault**
return true;
}
else
return false;
}
else if (x == t->key)
{
return false;
}
else
{
insert(x, t->right);
if (insert(x, t->right)){
t->size++; **Segmentation fault**
return true;
}
else
return false;
}
}
【问题讨论】:
-
使用调试器逐行执行程序时,您注意到了什么?
-
还有:你如何确保
left和right在这行NULL不是(t->left->size) + 1 + (t->right->size); -
当我使用 gdb 单步执行我的程序时,我得到:
Program received signal SIGSEGV, Segmentation fault. 0x0000000000401bbf in BinarySearchTree<std::string>::insert (this=0x7fffffffe390, x="1628879936", t=0x0) at BinarySearchTree.h:437 437 t->size++;这里是变量值(gdb) print t $1 = (BinarySearchTree<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::BinaryNode *) 0x0 (gdb) print t.size() Cannot access memory at address 0x30
标签: c++ insert segmentation-fault size binary-search-tree