1

I am receiving a segmentation fault while searching through a binary tree for a match. It does not give me a segmentation fault if a match is found but if it does not find anything it isn't finishing properly. Could someone point me in the right direction? What am i doing wrong.

void search() {
    char temp,temp1[15];
    struct node *s=root;
    int i=0;

    do{
        printf("Enter Name To Be Searched\n");
        scanf("%s",temp1);
        getchar();
        i=0;
        s=root;
        while(s!=NULL && i==0){
            if(strcmp(s->data,temp1)< 0)
                s=s->right;
            if(strcmp(s->data,temp1)>0)
                s=s->left;
            if(strcmp(s->data,temp1)==0)
                i=1;
        }
        if(i==0)
            printf("Element Not Found\n");
        else
            printf("Element Found\n");
        printf("Enter More Elements[Y/N]:\n");
        temp=getchar();
        printf("%c", temp);
    }while(temp=='y');
}
1
  • "It does not give me a segmentation fault if a match is found" Well that eliminates several possible reasons for your fault. Did you run this in a debugger before coming here with it? Commented Nov 8, 2013 at 18:54

2 Answers 2

3

You change s and then compare it again in the next if statement. Also think about if something is not bigger then zero neither smaller, then it must be equal.

while (s!=NULL) {
    const int cmp = strcmp(s->data,temp1);
    if (cmp < 0) 
        s = s->right;
    else if (cmp > 0)
        s = s->left;
    else {
        i = 1;
        break;
    }
}

Try that.

Sign up to request clarification or add additional context in comments.

2 Comments

Perhaps expand on this theme and stop calling the same function unnecessarily. There should only be one strcmp() in that loop and its result should be retained for evaluations therein. (and +1)
@fonZ No, I mean the two calls to the same proc with the same parameters within that loop are not needed. Call it once, saving the result in a temp, and run your if-else-if-else logic over the temp; not another call to strcmp(). Btw, the optimizer will likely do this anyway if it has any brains, but the code should do it regardless.
0

Probably your child node pointers are not null if there are no child nodes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.