Trying on Fedora gcc the following code for a simple Linked List adding new node to the tail of the list. No error in compilation. During execution, it is showing Segmentation Fault, Core Dumped. On MS Windows, it is working.
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *next;
};
void insertion(struct Node *);
void display(struct Node *);
int main(void)
{
struct Node *head;
head=NULL;
head->next=NULL;
int choice, cont;
do
{
printf("1.Insert 2.Display 3.Exit");
scanf("%d",&choice);
if(choice==1)
{
insertion(head);
}
else if(choice==2)
{
display(head);
}
else if(choice==3)
{
exit(0);
}
else
{
printf("Wrong choice");
}
printf("Continue? Press 1 otherwise 0:");
scanf("%d",&cont);
}while(cont==1);
return 0;
}
void insertion(struct Node *start)
{
int data;
struct Node *temp=NULL;
temp->next=NULL;
struct Node *mnew=NULL;
mnew->next=NULL;
mnew=(struct Node *)malloc(sizeof(struct Node));
printf("Enter data:");
scanf("%d",&data);
mnew->data=data;
if(start==NULL)
{
start=mnew;
}
else if(start!=NULL && start->next==NULL)
{
start->next=mnew;
}
else
{
temp=start;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=mnew;
}
}
void display(struct Node *start)
{
struct Node *temp=NULL;
temp->next=NULL;
if(start==NULL)
{
printf("\nNothing to display!");
}
else if(start!=NULL && start->next==NULL)
{
printf("%d",start->data);
}
else
{
temp=start;
while(temp!=NULL)
{
printf("%d",temp->data);
temp=temp->next;
}
}
}
Your help is appreciated.
start=mnew;does not changeheadmain value..... You should study something about pointers.