Getting core dump in simple tree program

Hi,
I was writing simple tree program and getting core dump during the traversal of tree.Could anyone provide me some insight.

#include<iostream>
using namespace std;

struct node
{
int data;
struct node *left;
struct node *right;
};

node *root =NULL;

void create_tree(int data)
{
node *temp = new node;
temp->data = data;
temp->left =NULL;
temp->right =NULL;

if(root ==NULL)
root =temp;

else
{
node *p =root;
node *trail =NULL;
while(p!=NULL)
{
trail=p;
if(p->data > data)
{
p =p->left;
}
else
{
p=p->right;
}
}
if(trail==NULL)
{
root=temp;
return;
}

if(trail->data > data)
{
trail->left =temp;
}
else
{
trail->right = temp;
}
}
}

void preorder_traverse(node *s)
{
cout<<"traversing data"<<" " ;
if(root)
{
cout<<s->data<<" ";
preorder_traverse(s->left);
preorder_traverse(s->right);
}
}

int main()
{
int data;
for(int i=0;i<3;i++)
{
cout<<"Enter data";
cin>>data;
create_tree(data);
}
cout<<"traverse :"<<endl;
preorder_traverse(root);

return 0;
}

1
2
3
4
5
6
7
8
9
10
void preorder_traverse(node *s)
{ 
  cout<<"traversing data"<<" " ;	
  if(root)	
  {
    cout<<s->data<<" "; //dereferencing NULL pointer
    preorder_traverse(s->left);
    preorder_traverse(s->right);
  }
}
Thanks a lot for your reply. Could you Pleas give some insight to fix this issue. I had impression that root is
global pointer and adding the the element into create_tree function will impact root pointer which can be use
for printing the element
I don't see a problem in create_tree(), but you should check for NULL of the node in the traverse
Topic archived. No new replies allowed.