Search code examples
clinked-listsegmentation-faultdynamic-memory-allocation

segmentation fault linked list


I see some similar topic but they didn't help me. I have make linked list, and a function to insert elements.

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

struct node* head;

void insert(struct node* head,int x);
int main(){
    struct node* head = (struct node*) malloc(sizeof(struct node));
    int x;
    while(1){
        printf("Please enter number\n");
        scanf("%i", &x);
        insert(head,x);
        print(head); // function that works
    }
    return 0;
}
void insert(struct node* head,int x){
    struct node* temp = malloc(sizeof(struct node));
    temp->data = x;
    temp->next = NULL;
    if(head->next != NULL) temp->next = head;
    head = temp;
    free(temp);
}

GDB says that I'm getting segmentation fault on the line with the if construction:

if(head->next != NULL) temp->next = head;

Where is my mistake ?


Solution

  • Yes ofcourse it will give segmentation fault. In if condition you are accessing head->next. head is just pointer of type struct node. First allocate the memory space and then access the field. Right now you are accessing (head->next) which is some inappropriate address in the memory and kernel gives "segmentation fault" to the process. For e.g do struct node* head = malloc(sizeof(struct node)); and then one can access head->next.