James James - 3 months ago 17
C Question

Segmentation Fault on Linked List Using C

I am new to C and try to learn how to implement C on linked list. I am really confused why I can't access myList in the main function? because when I try to

myList->data
, it's segmentation fault. I think there's some error in my addtohead function?
Below is my code:

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

typedef struct NODE{
int data;
struct NODE *next;
}node;

node * myList;

node * addToHead(node*, int);
void printList();

int main(){
myList = NULL;
int input;
while (scanf("%i",&input) == 1){
addToHead(myList, input);
printf("%d \n", myList->data);
}

printf("My List:\n");
printList(myList);
return 0;
}

node* addToHead(node* head, int newData){
node *temp = (node *)malloc(sizeof(node));
temp -> data = newData;
temp -> next = NULL;
if(head != NULL){
temp -> next = head;
}
head = temp;
return head;
}

void printList(node* head){
node *temp = head;
while(temp != NULL){
printf("%d ", temp->data);
temp = temp -> next;
}
printf("\n");
}

LPs LPs
Answer

Your addToHead function is supposed to return the mallocated memory back to caller.

So you should assign the return value to mylist at first:

int main(){
    node *myList = NULL;
    int input;
    while (scanf("%i",&input) == 1){
           myList = addToHead(myList, input);
           printf("%d \n", myList->data);
       }

    printf("My List:\n");
    printList(myList);
    return 0;
}

Into your addToHead function you wrote

head = temp;

But head has local scope and the assigned value is not reflected to the pointer myList.

To do so you have to use pointer to pointer.

int main(){
    node *myList = NULL;
    int input;
    while (scanf("%i",&input) == 1)
    {
       if (addToHead(&myList, input) == true)
       {
           printf("%d \n", myList->data);
       }
       else
       {
           fprintf(stderr, "Error addToHead\n");
       }
    }

    return 0;
}

bool addToHead(node** head, int newData){
    node *temp = malloc(sizeof(node));
    if (temp != NULL)
    {
       temp -> data = newData;
       temp -> next = NULL;
       if(head != NULL)
       {
          temp -> next = *head;
       }

       *head = temp;

       return true;
   }

   return false;
}

Finally always remember to check the malloc return value: it can fail.

Comments