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);
}