Sunday, 15 July 2012

c - Binary Search Tree Issues -



c - Binary Search Tree Issues -

i'm working on binary tree list tacked on data, yet can't tell if list beingness populated or not. code runs alright when seek phone call print out tree freeze in code. believe beingness pointed it's obvious there flaw in logic somewhere.

struct declarations

typedef struct linelist { int linenum; list *next; }list; typedef struct nodetag{ char data[80]; list *lines; struct nodetag *left; struct nodetag *right; } node;

declaration , pass function main

node *root = null; readfromfile(argv[1], root);

readfromfile(working function) calls insertword

insertword(root, keyword, linenum);

insertword, addtolist functions(problem area)

node *allocatenode(char *data, int line) { node *root; list *newnum; if(!(root = (node *) malloc (sizeof(node)))) printf( "fatal malloc error!\n" ), exit(1); strcpy(root->data, data); //copy word (root)->left = (root)->right = root->lines = null; //initialize if (!(newnum =(list *) malloc (sizeof(list)))) printf( "fatal malloc error!\n" ), exit(1); newnum->linenum = line; root->lines = newnum; homecoming root; } /**************************************************************** iterative insert */ node *insertword(node *root, char *data, int line) { node *ptr_root = root; printf("inserting %s\n", data); if(root == null) { root = allocatenode(data, line); homecoming root; } while(ptr_root) { if (strcmp(data, ptr_root->data > 0)) { if(ptr_root->right) ptr_root = ptr_root->right; //traverse right else ptr_root->right = allocatenode(data, line); } else if (strcmp(data, ptr_root->data) < 0) { if(ptr_root->left) //traverse left ptr_root = ptr_root->left; else ptr_root->left = allocatenode(data, line); } else { printf("node in tree!\n"); addtolist(ptr_root, line); } } printf("5\n"); homecoming root; } void printtreeinorder(node *root)//simple print, freeze on phone call function { if(root) { printtreeinorder(root->left); printf( "%s\n", root->data ); printtreeinorder(root->right); } return; }

let's @ insertword():

at end of while loop, know ptr_root == null. we allocate memory ptr_root. we initialize contents of ptr_root. we perform memory leak on ptr_root.

note need retain parent of new node, , need point left or right pointer new node.

it sounds understand how utilize debugger. if that's true, should able see root doesn't alter between calls insertword().

in code you've posted attempted fix, you're missing 1 key thing. let's @ function:

void foo(node *root) { printf("before malloc: %p\n", root); root = malloc(sizeof(node)); printf("after malloc: %p\n", root); } int main() { node *root = null; printf("before function: %p\n", root); foo(root); printf("after function: %p\n", root); }

this code produce:

before function: 0x0 before malloc: 0x0 after malloc: 0x123ab129 after function: 0x0

note changes value of root not propagated out of function. things alter *root though.

c binary-tree

No comments:

Post a Comment