0

This program always gives me a Segmentation Fault when I add the last node, what could be the possible reason. it only comes while adding the last node, I have commented the line in which I get the segmentation fault. I'm new to programming.

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

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


struct node *createNode(int val){
        struct node *ret=(struct node *)malloc(sizeof(struct node));
        ret->data=val;
        ret->next=NULL;
        return ret;
}


struct node *addNode(struct node *ll,int val){
        //Gives error here for the last node, it creates the node succesfull but this step give segmentation fault
        struct node *new_node=createNode(val);
        new_node->next=ll;
        return new_node;
}

void printList(struct node *ll){
        printf("printing list");
        struct node *temp=ll;
        while(temp->next){
                printf("%d ->",temp->data);
                temp=temp->next;
        }
}

int main(){
        struct node *head;
        head=addNode(head,3);
        head=addNode(head,5);
        head=addNode(head,1);
        head=addNode(head,9);
        printList(head);
}

3 Answers3

3
 struct node *head;

head is uninitialized so using uninitialized variables leads to undefined behavior. Initialize your head to NULL before adding nodes.

 struct node *head = NULL;

DO NOT CAST MALLOC AND FAMILY

Community
  • 1
  • 1
Gopi
  • 19,784
  • 4
  • 24
  • 36
1

Assign NULL to the head.

 struct node * head=NULL;

because in addnode you are doing like this,

 new_node->next=ll;

Then while printing the node make the condition like this,

while(node){
...
}

If you use the node>next you will loss the last value in the linked list.

Don't cast the malloc and family.

Community
  • 1
  • 1
Karthikeyan.R.S
  • 3,991
  • 1
  • 19
  • 31
0

you are facing this problem because when you are adding the new node in the link list you are adding this node as a start of the linklist.

Initially:

struct node* head; //This is not NULL.Big mistake by you.But this is not the only problem.

The segmentation fault is there because you are trying to access the invalid memory location in printList(), as the last node pointer( which was firstly declared by you as head) is not pointing to any valid memory location.Try commenting the call to printList() you will see that bug goes.But this is not the solution you are looking for, even if you initialize the head to NULL you will face the problem where last node will not get printed.for this use:-

while(temp)

in printList().

OldSchool
  • 2,123
  • 4
  • 23
  • 45