Binary Search Tree C

Saad Farooq

I have a problem with insertion in Binary search tree in C. I have the following definition of a binary tree(please ignore line numbers):

struct WordBT {
    char *term;
    struct WordBT *right;
    struct WordBT *left;
};

typedef struct WordBT* WordPtrBT;
WordPtrBT mainListBT;

And my insert function:

int addlistBT(char *term, char *file, WordPtrBT curr) {
    if (curr == NULL) {
        WordPtrBT temp =  (WordPtrBT)malloc(sizeof(WordPtrBT));
        temp->term = term;
        curr = temp;
        return 1;
    }

    int test = //some test;
    if (test == 0) {
        return 0;
    }
    if (test > 0) {
        addlistBT(term, file, curr->left);
    }
    if (test < 0) {
        addlistBT(term, file, curr->right);
    }
}

Then i call

addlistBT(term, file, mainListBT);

I get a seg fault later on in the program. When i debug with gdb this is what i see:

                        curr = temp;
(gdb) p temp
$7 = (WordPtrBT) 0x60a2a0
(gdb) p curr
$8 = (WordPtrBT) 0x0
(gdb) p mainListBT
$9 = (WordPtrBT) 0x0
(gdb) n
93                      addfileBT(file, curr->file);
(gdb) p temp
$10 = (WordPtrBT) 0x60a2a0
(gdb) p curr
$11 = (WordPtrBT) 0x60a2a0
(gdb) p mainListBT
$12 = (WordPtrBT) 0x0

Now my question is that since mainListBT is defined as a pointer then why isnt mainListBT assigned the pointer to temp? Thanks

Bobb Dizzles

What you should do: call using addlistBT(term, file, &mainListBT); Then change the addlist function to the following:

 81 int addlistBT(char *term, char *file, WordPtrBT *curr){
 86         if(!(*curr)){
 87                 WordPtrBT temp =  (WordPtrBT)malloc(sizeof(struct WordBT));
 88                 temp->term = term;
 92                 *curr = temp;
 94                 return 1;
 95         }
 96         int test = //some test;
 97         if(test == 0){  return 0;}
101         if(test > 0){   addlistBT(term, file, &(*curr)->left);}
104         if(test < 0){   addlistBT(term, file, &(*curr)->right);}
107 }

some pointer magic...

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related