Home > Back-end >  "Segmentation fault" error message for simple list in c
"Segmentation fault" error message for simple list in c

Time:12-16

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

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

void printList(struct node *head);

int main() {
    struct node* head;
    head->data =10;
    head->next = NULL;
    printList(head);    
}


void printList(struct node *head){
    struct node *ptr = head;
    if (ptr->next = NULL){
        printf("list is empty");
    }
    while(ptr != NULL){
        printf("%d", ptr->data);
        ptr = ptr->next;
    }
}

I'm try to implement a simple list structure, but I am getting a segmentation error.

Any clues to why?

CodePudding user response:

There are some issues with your code

  1. In main function, the head pointer is not initialized. You need to allocate memory for the object it will point to.
struct node* head = malloc(sizeof(struct node));
  1. In printList function, if statement using '=' assignment operator instead of '==' comparison operator
if (ptr->next == NULL){
    printf("list is empty");
}

CodePudding user response:

There are different problems here. Check better about how pointers works in c.

When you write something like this struct node* head; you only added an address memory pointing to another undefined zone of space. So, in order to generate something you should alloc some memory in it before accessing that zone of memory and setting data.

Another problem is the first if condition in printList function that should have '==' instead of '='

  • Related