将 if 语句与指针一起使用时出现分段错误(BST 树)
Segmentation fault when using if statement with pointers (BST tree)
我正在尝试用 C 实现二叉搜索树,更具体地说是寻找前身。但是,每当我尝试 运行 该程序时,我都会得到分段库。这是有问题的代码:
#include <stdio.h>
#include <stdlib.h>
struct tree
{
int a;
tree *left;
tree *right;
tree *prev;
}*root=NULL;
tree *searchSpecific (tree *root, int val)
{
tree *x=root;
if (!x)
{
return NULL;
}
else
{
while(x && val!=x->a)
{
if (val>x->a)
x=x->left;
else x=x->right;
}
}
return x;
}
int previous(tree *root, int f)
{
tree *x=searchSpecific(root,f);
if(x->left)
{
x=x->left;
while(x->right) x = x->right;
return x->a;
}
tree *temp;
do
{
temp = x;
x = x->prev;
} while(x && (x->right != temp));
return x->a;
}
段错误出现在previous()函数中的if语句if(x->left)处。我想检查有问题的节点是否存在,但程序每次都崩溃,我不知道它有什么问题..
由于 searchSpecific
可能 return NULL
,您需要保护您的代码免受它的影响,并在访问其成员之一之前检查 x
:
tree *x=searchSpecific(root,f);
if (x != NULL && x->left)
出现分段错误的原因有多种,例如:
- x未定义,可能是你的*searchSpecific函数造成的
- x 是 NULL,因为你的函数 returns 一个 NULL 指针
- x->left 为 NULL,这意味着尝试访问它会导致一些不好的事情发生
因此,我将如何着手执行此操作将尝试使用如下简单的 if 语句检查返回的树是否为空:
if (x == NULL) {
/* throw error or not found message */
}
我还建议您在对树进行任何操作之前动态地为其分配内存,方法是使用以下代码创建一个可重用的函数,例如 create_tree():
tree create_tree(int data) {
tree *x;
x = malloc(sizeof(tree));
x->a = data;
x->left = x->right = x->prev = NULL;
return x;
}
为什么?请注意,在您的代码片段中,您只需声明
tree *some_tree_name;
每次你尝试用它做某事时都非常危险,可能会导致你的代码在稍后的 do/while 循环中崩溃。
我正在尝试用 C 实现二叉搜索树,更具体地说是寻找前身。但是,每当我尝试 运行 该程序时,我都会得到分段库。这是有问题的代码:
#include <stdio.h>
#include <stdlib.h>
struct tree
{
int a;
tree *left;
tree *right;
tree *prev;
}*root=NULL;
tree *searchSpecific (tree *root, int val)
{
tree *x=root;
if (!x)
{
return NULL;
}
else
{
while(x && val!=x->a)
{
if (val>x->a)
x=x->left;
else x=x->right;
}
}
return x;
}
int previous(tree *root, int f)
{
tree *x=searchSpecific(root,f);
if(x->left)
{
x=x->left;
while(x->right) x = x->right;
return x->a;
}
tree *temp;
do
{
temp = x;
x = x->prev;
} while(x && (x->right != temp));
return x->a;
}
段错误出现在previous()函数中的if语句if(x->left)处。我想检查有问题的节点是否存在,但程序每次都崩溃,我不知道它有什么问题..
由于 searchSpecific
可能 return NULL
,您需要保护您的代码免受它的影响,并在访问其成员之一之前检查 x
:
tree *x=searchSpecific(root,f);
if (x != NULL && x->left)
出现分段错误的原因有多种,例如:
- x未定义,可能是你的*searchSpecific函数造成的
- x 是 NULL,因为你的函数 returns 一个 NULL 指针
- x->left 为 NULL,这意味着尝试访问它会导致一些不好的事情发生
因此,我将如何着手执行此操作将尝试使用如下简单的 if 语句检查返回的树是否为空:
if (x == NULL) {
/* throw error or not found message */
}
我还建议您在对树进行任何操作之前动态地为其分配内存,方法是使用以下代码创建一个可重用的函数,例如 create_tree():
tree create_tree(int data) {
tree *x;
x = malloc(sizeof(tree));
x->a = data;
x->left = x->right = x->prev = NULL;
return x;
}
为什么?请注意,在您的代码片段中,您只需声明
tree *some_tree_name;
每次你尝试用它做某事时都非常危险,可能会导致你的代码在稍后的 do/while 循环中崩溃。