Hi Guys. I tried creating an insert into tree datastructure which is causing core dump.

Please identify the issue...

Here is the code

#include<iostream>
#include<string>
#include<stdlib.h>

using namespace std;

//Global Data

struct Tree
{
	Tree* right;
	Tree* left;
	int element;
};
typedef struct Tree* TreeData;

//Function Declaration

void insert(TreeData &data,int element);


int main()
{
	string tree_value;
	int tree_elem;
	TreeData main_tree;
	cout<<"Enter Numbers to Insert in Tree"<<endl;
	cout<<"TO END THE SEQUENCE ENTER "<<endl;
	while(1)
	{

	cin>>tree_value;
	if(!tree_value.compare("*")==0)
	{
	tree_elem=atoi(tree_value.c_str());
	cout<<"Tree element is"<<tree_elem<<endl;
	insert(main_tree,tree_elem);
	}
	else
	{
		exit(0);
	}
	}

	cout<<main_tree->element<<endl;
}

void insert(TreeData &data,int element)
{
	cout<<"Inside Insert"<<endl;
	if(data == NULL)
	{
		cout<<"Data is NULL"<<endl;
		data=(TreeData)malloc(sizeof(TreeData));
		if(data==NULL)
		{

			cout<<"Error Allocating Memory"<<endl;
			exit(0);
		}
		else
		{
			cout<<"element"<<element<<endl;
			data->element=element;
			data->right=NULL;
			data->left=NULL;
		}

	}
	else
	{
		if(element<data->element)
		{
			insert(data->right,element);
		}
		else if(element>data->element)
		{
			insert(data->left,element);
		}
	}

}

Recommended Answers

All 2 Replies

What input sequence causes core dump?
seems to work on my machine...

Also, please use code tags!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.