I'm trying to implement a binary search tree in C, more specifically looking for the predecessor. However, whenever I try to run the program I get the segmentation vault. Here's the code in question:
#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;
}
The segfault appears at the if statement if(x->left) in the previous() function. I want to check if the node in question exists, but the program crashes every time and I have no idea what is wrong with it..
Since
searchSpecific
may returnNULL
, you need to protect your code from it, and checkx
before accessing one of its members: