简体   繁体   中英

Binary tree in C - Segmentation fault

#include <stdio.h>
#include <stdlib.h>

typedef struct nod{
    int data;
    struct nod *left,*right;
}NOD;

NOD * generate(NOD * root)
{
    NOD *r,*p;
    int d=-1,value,line,position,i,f,v;
    if(root==NULL)
    {
        do{
            printf("Would you like to create the root node?\n\n1 - yes\n0 - no\n");
            scanf("%d",&d);
            switch(d)
            {
                case 1:
                    printf("Value=");
                    scanf("%d",&value);
                    root=add_root(value);
                    break;
                case 0:
                    return NULL;
                    break;
                default:
                    printf("Command unrecognized!\n");
                    break;
            }
        } while(d==-1);
        if(root!=NULL)
                printf("Root node successfully created!\n");
        else
            printf("Error: could not create root node!\n");
        d=-1;
        do{
            printf("Continue adding nodes?\n\n1 - yes\n0 - no\n");
            scanf("%d",&d);
            switch(d)
            {
                case 1:
                    printf("Insert the line and the position of the node you wish to add (root node has line=0, position=0)\nLine=");
                    scanf("%d",&line);
                    printf("Position ( less or equal with 2^$line-1 )=");
                    scanf("%d",&position);
                    printf("Value=");
                    scanf("%d",&value);
                    r=p=root;
                    for(i=line-1;i=0;i--)  
                    {
                        f=power(2,i);
                        if(position & f == f)   // if the i-(st,nd,rd,th) bit of "position" is 1, then (position & f == f) is true and *r will go right
                        {
                            p=r;
                            r=r->right;
                            v=1;
                        }
                        else
                        {
                            p=r;
                            r=r->left;
                            v=0;
                        }
                    }
                    if(v==0)
                        p=add_left(&r,value);
                    if(v==1)
                        p=add_right(&r,value);

                    break;
                case 0:
                    return root;
                    break;
                default:
                    printf("Command unrecognized!\n");
                    break;
            }
        } while(d==-1);
    }
    else
    {
        ...
    }

NOD * add_left(NOD **p,int value)
{
    NOD * r;
    r=malloc(sizeof(NOD));
    r->data=value;
    r->left=NULL;
    r->right=NULL;
    (*p)->left=r;
    return r;
}

NOD * add_right(NOD **p,int value)
{
    NOD * r;
    r=malloc(sizeof(NOD));
    r->data=value;
    r->left=NULL;
    r->right=NULL;
    (*p)->right=r;
    return r;
}

NOD * add_root(int value)
{
    NOD * x;
    x=malloc(sizeof(NOD));
    x->data=value;
    x->left=NULL;
    x->right=NULL;
    return x;
}

}
int main() {
    NOD *root=NULL;
    root=generate(root);
    return 0;
}

I tried make a program that creates a binary tree but I keep getting SIGSEGV Segmentation fault and I don't understand why. Can you please tell me what I did wrong?

if(position & f == f)   // if the i-(st,nd,rd,th) bit of "*position*" is 1,
                        // then (position & f == f) is true and *r will go right

What do you think about this part?

  • line is the level of the tree (root has line=0)

  • position is the position of node from left to right (root has position=0)

You already have bolded a problematic part:

if(position & f == f) 

== has higher precedence than & , so that is parsed as

if(position & (f == f))

and is the same as if (position & 1) , not what you want.

Further, you have the wrong loop condition

for(i=line-1;i=0;i--)

the test should probably be i >= 0 , otherwise the loop is never executed ( i = 0 is an assignment that evaluates to 0).

If these are fixed and the loop is executed, after the first iteration r is a nullpointer, then the next loop iteration causes the crash in r = r->right; , or, if the loop iterates only once, add_left(&r,value); (or add_right ) dereferences a nullpointer on the penultimate line trying to access its left (resp. right ) pointer:

NOD * add_left(NOD **p,int value)
{
    NOD * r;
    r=malloc(sizeof(NOD));
    r->data=value;
    r->left=NULL;
    r->right=NULL;
    (*p)->left=r;          // *p == NULL here
    return r;
}

In this line

for(i=line-1;i=0;i--)

I think you meant

for(i=line-1;i!=0;i--)

Otherwise the loop will not execute ( i=0 evaluates to false ). which causes v to have undefined value (as it is never initialized). While this most likely will not result in segfault, it will cause memory leak as you overide the left/right subtree of the root.

Also, the default switch branch does not change the scanned value of d , which means you proceed with a NULL root (the error branch that checks for root != NULL ) does not exit the function)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM