why do i have a segmentation fault in the link list?

The argument of the calls of scanf

scanf("%i", x);
scanf("%i", y);
scanf("%i", n);

is incorrect. You have to pass the variables by reference

scanf("%i", &x);
scanf("%i", &y);
scanf("%i", &n);

This while loop

while(n == 1){
  
  if (temp->num < y){
    if (temp->right == NULL){
      node* a = malloc(sizeof(node));
      temp->right = a;
      temp->right->num = y;
      break;
    }
    else{
      temp = temp->right;
    }
  }

printf("Want to stop? Yes(1) or No (1)?");
scanf("%i", n);

}

can invoke undefined behavior because for a newly allocated node

    if (temp->right == NULL){
      node* a = malloc(sizeof(node));
      temp->right = a;
      temp->right->num = y;
      break;
    }

you are not setting its data member right to NULL. So it has indeterminate value. As a result this if statement

    if (temp->right == NULL){

after this statement

      temp = temp->right;

compares this indeterminate value with NULL.

And it seems there is a typo in the outputted string

printf("Want to stop? Yes(1) or No (1)?");
                        ^^^^       ^^^

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top