Segmentation Fault

I am trying to create a binary search tree. The program compiles but when I run it I get a segmentation fault error. If somebody could please show me exactly where my mistake is I would really appreciate it.

struct TreeItem {
char *key;
char *winG;
};

struct TreeNode {
TreeItem item;
TreeNode * left;
TreeNode * right;

TreeNode(TreeItem value, TreeNode * lval, TreeNode * rval)
{
item = value;
left = lval;
right = rval;
}
};

typedef TreeNode * TreePtr;

TreePtr sortInit(ifstream & input)
{
//tree to be returned
TreePtr tree;

int usedSize = 0;
char buf[BUFFERSIZE];
char *bufptr = buf;

//array of treeItems
TreeItem items [64];
int arrIn = 0;

while (input.getline(bufptr,BUFFERSIZE)) //read first line for team
{
//insert into array and set key field
items [arrIn].key=bufptr;

//read second lind for wins
input.getline(bufptr,BUFFERSIZE);

//set the win games field
items [arrIn].winG = bufptr;

//increase position and used size
arrIn++;
usedSize++;
}
//sort the array using the selection sort algorithm
for (int pos = 0; pos < usedSize; pos++){
int min = pos;
for (int i = pos+1; i < usedSize; i++)
{
if (strcmp(items[i].key, items[min].key) < 0){
min = i;
}
}
TreeItem tmp = items[pos];
items[pos] = items[min];
items[min] = tmp;
}
//create binary search tree
tree = createTree(items, 0, usedSize-1);
return tree;
}
TreePtr createTree(TreeItem arr[], int first, int last) {

if (first > last) return NULL;
// same as (first + last)/2, avoids overflow.
int mid = (first + last) / 2;

TreePtr root;
root->item = arr[mid];

root->left = createTree(arr, first, mid-1);
root->right = createTree(arr, mid+1, last);

return root;
}
You've made a rod for your own back with your impenetrable use of pointers without using the heap.

You can begin to fix it by using value types rather than pointers in TreeItem.

Topic archived. No new replies allowed.