1
votes

Having seg fault erros with my code posted below. I am new to C and have been having some trouble with it. Basically in my main I made a struct node* head (pointer to a struct node) and assigned it to NULL. I then send the struct node * head to the push function that should insert user defined integers into the front of the list. I believe I am having issues inside the push function, any help would be very aprecciated.

~Thanks

//node.h

struct node{
        int val;
        struct node* next;
 };

 int length(struct node *);
 struct node* push(struct node *, int);
 void print(struct node *, int);


 //node.c

 #include "./node.h"
 #include<stdlib.h>
 #include<stdio.h>

int length(struct node *current){
       if(current->next != NULL)
          return 1 + length(current->next);
       else
          return 1;
}

struct node* push(struct node *head, int num){

   struct node *temp = malloc(sizeof(struct node));
   temp->val = num;
   temp->next = head;
   head = temp;
   return head;
}

void print(struct node* head, int size){
   printf("The list is %i", size);
   printf(" long \n");
   struct node* temp;
   temp = head;
   while(temp != NULL){
   printf("%d", temp->val);
   printf(" ");
   temp = temp->next;
   }
   printf(" \n");
 }


 //main program

 #include "./node.h"
 #include<stdlib.h>
 #include<stdio.h>

  int main(){

    char ans;
    int num;
    struct node* head = NULL;

    do{
       printf("Enter a integer for linked list: ");
       scanf("%d", &num);
       head = push(head, num);
       printf("Add another integer to linked list? (y or n) ");
       scanf("%1s", &ans);
       }while(ans == 'y');

       print(head, length(head));

       return 0;
       }
1
char ans; --> char ans[2];, ans == 'y' --> *ans == 'y'BLUEPIXY

1 Answers

1
votes

scanf will read n+1 characters into the provided buffer when you use %ns because of the null terminator.

Use a buffer of size 2 (char ans[2];) and check the first character (ans[0] == 'y'). You will also no longer need to take the address of ans when calling scanf).