Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Search Tree C

Tags:

c

gdb

binary-tree

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

like image 524
Saad Farooq Avatar asked Jan 31 '26 17:01

Saad Farooq


1 Answers

There are multiple bugs in your program.

First, you are doing an equivalent of this:

void fn(int x) {
  x = 1;
}

int main() {
  x = 0;
  fn(x);
  // you expect x == 1 here, but you *should* expect 0.
}

Just as you need to pass &x instead of x into foo(), you need to pass &mainListBT into addlistBT() (and change its signature).

The second obvious bug is that this line:

WordPtrBT temp =  (WordPtrBT)malloc(sizeof(WordPtrBT));

allocates space for a pointer, when you want it to allocate space for the structure. It should be

WordPtrBT temp =  malloc(sizeof(*temp));

or

WordPtrBT temp =  malloc(sizeof(struct WordBT));

(and you should never cast result of malloc call).

like image 74
Employed Russian Avatar answered Feb 02 '26 10:02

Employed Russian