need help finding error in binary tree code

A

andrew browning

gbd says the segmentation fault is being generated in the insert
function.

//CONSTRUCTOR
tree():data(value_type()), left(0), right(0){};
tree(value_type vt, tree* l = 0, tree* r = 0):
data(vt), left(l), right(r) {};

//PRIVATE MEMBERS

value_type data;

tree *left;

tree *right;

//INSERT AND ADD NODE FUNCTIONS

tree::tree* tree::newNode(value_type new_data){
tree* node = new tree (data);
node->data = data;
node->left = 0;
node->right= 0;
return node;
}

tree::tree* tree::insert(tree* node, value_type new_data){
if (node == 0){
return(newNode(data));
}else

if(data <= node->data){
node->left = insert(node->left, data);
}else
node->right = insert(node->right, data);
return node;
}

//DRIVER

#include<iostream>
#include "tree.h"
using namespace std;
using namespace abrowning_13;

int main(){

tree t1;
tree* tree_ptr;
int user_input;

while(cin.peek() != EOF){
t1.insert(tree_ptr, user_input);
}
t1.inorder_print(tree_ptr);


return 0;

}
 
T

Thomas J. Gritzan

andrew said:
gbd says the segmentation fault is being generated in the insert
function.

//CONSTRUCTOR
tree():data(value_type()), left(0), right(0){};
tree(value_type vt, tree* l = 0, tree* r = 0):
data(vt), left(l), right(r) {};

//PRIVATE MEMBERS

value_type data;

tree *left;

tree *right;

//INSERT AND ADD NODE FUNCTIONS

tree::tree* tree::newNode(value_type new_data){
tree* node = new tree (data);
node->data = data;

new_data, not data.
node->left = 0;
node->right= 0;
return node;
}

tree::tree* tree::insert(tree* node, value_type new_data){
if (node == 0){
return(newNode(data));

new_data again.
}else

if(data <= node->data){
node->left = insert(node->left, data);
}else
node->right = insert(node->right, data);
return node;
}

The insert function ignores the class instance, it should be a static
function, as should newNode (which is completly useless, since new
tree(new_data) does the same).
//DRIVER

#include<iostream>
#include "tree.h"
using namespace std;
using namespace abrowning_13;

int main(){

tree t1;
tree* tree_ptr;
int user_input;

while(cin.peek() != EOF){
t1.insert(tree_ptr, user_input);

You use uninitialized tree_ptr, that causes UB and yields to
segmentation fault.

Thomas
 
A

andrew browning

i fixed new_data and made it data to comply with the class instance.
i'm a little stuck, however on how to initialize tree_ptr... pointers
are a little arcane at this point. what do i initialize it to point to?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,992
Messages
2,570,220
Members
46,807
Latest member
ryef

Latest Threads

Top