我认为这肯定是简单的问题,但我不知道怎么了。
gdb说
Program received signal SIGSEGV, Segmentation fault.
0x000055555555543e in searchNode (root=0x0, X=1) at problem1.c:40
40 while(cursor->value != X || cursor != NULL)
插入和搜索功能
typedef struct TreeNode
{
int value;
struct TreeNode *left;
struct TreeNode *right;
struct TreeNode *parent;
} tree;
tree *insert(tree *root, int X)
{
tree *cursor = root;
tree *parent;
while(cursor != NULL)
{
parent = cursor;
if(X >= cursor->value)
cursor = cursor->right;
else
cursor = cursor->left;
}
cursor = (tree *)malloc(sizeof(tree));
cursor->value = X;
cursor->left = cursor->right = NULL;
cursor->parent = parent;
return cursor;
}
tree *searchNode(tree *root, int X)
{
tree *cursor = root;
while(cursor->value != X || cursor != NULL)
{
if(X >= cursor->value)
cursor = cursor->right;
else
cursor = cursor->left;
}
if(cursor == NULL)
return NULL;
else if(cursor->value == X)
return cursor;
}
主要功能
int main()
{
tree *root = (tree *)malloc(sizeof(tree));
root = NULL;
insert(root, 10);
insert(root ,20);
insert(root, 5);
insert(root, 1);
insert(root, 15);
insert(root, 20);
insert(root, 30);
insert(root, 100);
insert(root, 40);
insert(root, 50);
node = searchNode(root, 1);
}
据我所知,当我引用NULL指针时,分段错误大部分出现,但是我不认为搜索功能是错误的。 我认为我在插入函数或初始化树根时出错,但是我不知道怎么了。
答案 0 :(得分:1)
出于好奇,我调查了代码。
我认为搜索功能没有错
我不同意!
看下面这行代码:
while(cursor->value != X || cursor != NULL)
如果cursor
是NULL
会发生什么?已访问Undefined Behavior的cursor->value
(因为不允许访问NULL
)。这值得Segmentation fault
。
更好的是:
while (cursor != NULL && cursor->value != X)
或更短:
while (cursor && cursor->value != X)
从gdb调用OP的代码段
Program received signal SIGSEGV, Segmentation fault.
0x000055555555543e in searchNode (root=0x0, X=1) at problem1.c:40
40 while(cursor->value != X || cursor != NULL)
(乍一看我没有意识到)对我来说听起来很合理。
根据(root = 0x0
),似乎为空树调用了searchNode()
(root
是NULL
)。因此,tree *cursor = root;
使用cursor
指针(以及上面的其余部分)初始化NULL
。
答案 1 :(得分:0)
您的insert
函数的问题在于它无法更新root
的值。您返回了新的叶子节点,但是对跟踪root
可能没有多大用处。
要更改root
,您必须传递一个指向它的指针,例如:
insert(&root, 10);
然后您可以像这样更改功能。它遍历该树,传递一个指向当前节点的左或右分支的指针,直到发现该节点尚不存在,然后创建它。
tree *insert(tree **root, int X)
{
if(*root == NULL)
{
*root = (tree *)malloc(sizeof(tree));
(*root)->value = X;
(*root)->left = (*root)->right = (*root)->parent = NULL;
return(*root);
}
else
{
tree *ret;
if(X >= (*root)->value)
{
ret=insert(&(*root)->right, X);
(*root)->right->parent=*root;
}
else
{
ret=insert(&(*root)->left, X);
(*root)->left->parent=*root;
}
return ret;
}
}
因此,当您第一次调用它时,它将为您填充root
。第二次,它将传入指向root->right
的指针,该指针将成为您的root
函数中的新insert
,因为它是NULL
,所以将创建它。为了完整起见,它会更新parent
链接。