I am trying to insert node in a binary search tree, I am getting an access voilation error at line if(ptr->data== item) in searchNode() function. How can I remove it. I am new to debugging.
I am first trying to insert few nodes and then display them using display function. During insertion the program searches for the appropriate position of the node to be inserted and then inserts it. Program simply returns if node already exists.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* left;
struct node* right;
};
void searchNode(struct node* root,int item,struct node* loc,struct node *par)
{
struct node * ptr,*save;
if(root==NULL)
{
loc=NULL;
par=NULL;
return;
}
else
{
if(item==root->data)
{
par=NULL;loc=root; return;
}
else if(item < root->data)
{
save=root;ptr=root->left;
}
else if(item > root->data)
{
save=root;ptr=root->right;
}
while(ptr!=NULL)
{
if(ptr->data == item )
{
loc=ptr;
par=save;
return;
}
else if(ptr->data > item )
{
save=ptr;
ptr=ptr->left;
}
else
{
save=ptr;ptr=ptr->right;
}
}
loc=NULL;
par=save;
}
}
void insertNode(struct node* root,int item, struct node * loc)
{
struct node* par,*newNode;
searchNode(root,item,loc,par);
if(loc!=NULL)
return;
newNode=(struct node *)malloc(sizeof(struct node));
newNode->left=NULL;newNode->right=NULL;
if(par==NULL)
{
root=newNode;
}
else if(item< par->data)
{
par->left=newNode;
}
else if(item> par->data)
{
par->right=newNode;
}
}
void display(struct node* t, int level)
{
int i;
if(t)
{
display(t->right,level+1);
printf("\n");
for(i=0;i<level;i++)
printf(" ");
printf("%d",t->data);
display(t->left,level+1);
}
}
int main()
{
int n,data,i;
struct node* root,*loc;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&data);
insertNode(root,data,loc);
}
display(root,1);
getch();
return 0;
}
You are calling your insert method as:
and the
rootis passed by value as a result, any changes made to root in theinsertNodemethod will not be visible inmain. Since yourrootinmainis uninitialized, the same gets passed todisplaywhere you try to dereference the uninitialized pointer leading to undefined behavior.To fix this you either pass the address of
roottoinsertNodefunction or return the changed root from the function.