I have written a similar piece of code in C++ for Windows where I create a basic singly linked list, add data and display the list's content. I tried writing a similar kinda program in C this time for Linux. There seems to be no compiler error or run-time error, but when I try to call the function void insert()
, the program console tells me there is a segmentation error.
My code is included below :
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node* next;
}*nPtr;
nPtr head = NULL;
nPtr cur = NULL;
void insert(int Data);
void display();
int main(void)
{
int opr, data;
while (opr != 3)
{
printf("Choose operation on List. \n\n1. New Node. \n2. Display List.\n\n>>>");
scanf("%d", opr);
switch (opr)
{
case 1 :
printf("Enter data.\n");
scanf("%d", data);
insert(data);
break;
case 2 :
display();
break;
case 3 :
exit(0);
default :
printf("Invalid value.");
}
}
getchar();
}
void insert(int Data)
{
nPtr n = (nPtr) malloc(sizeof(nPtr));
if (n == NULL)
{
printf("Empty List.\n");
}
n->data = Data;
n->next = NULL;
if(head != NULL)
{
cur= head;
while (cur->next != NULL)
{
cur = cur->next;
}
cur->next = n;
}
else
{
head = n;
}
}
void display()
{
struct Node* n;
system("clear");
printf("List contains : \n\n");
while(n != NULL)
{
printf("\t->%d", n->data, "\n");
n = n->next;
}
}
When I run the code, there doesn't seem any problem or error at all. But when I call either of the 2 functions I created up there, there is an error which says "Segmentation fault". I'd assume something would be wrong with my malloc()
function in void insert()
, but I can't pin-point what's wrong in the void display()
method.