Unable to create a linked list in Linux using C - c

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.

The display() function never initializes n. The declaration should be:
nPtr n = head;

Related

Exception fault(Segmentation fault) creating a singly link list in c

Program to create a singly link list but an Exception error (Segmentation fault) occurs while printing the data stored in the link list, although the program runs and show output
.
//Program to create a singly link list
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct node
{
int data;
struct node *next;
};
void main()
{
struct node *head, *newnode, *temp;
head = 0;
int choice = 1;
while (choice)
{
if(choice==1)
{
newnode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data ");
scanf("%d", &newnode->data);
newnode->next;
if (head == 0)
{
head = temp = newnode;
}
else
{
temp->next = newnode;
temp = newnode;
}
printf("Do you want to continue - Press 1 to continue and 0 to terminate ");
scanf("%d", &choice);
}
}
temp = head;
while (temp != 0)
{
printf("%d\t", temp->data);/*Here it show Exception error(Segmentation fault)*/
temp = temp->next;
}
getch();
}
There is a typo in this statement
newnode->next;
It seems you mean
newnode->next = NULL;
Pay attention to that according to the C Standard the function main without parameters shall be declared like
int main( void )

Is this a correct implementation on circular linked list (Queue)?

I am trying to write a code on circular queue using linked list.
I stumbled to a problem where i don't exactly know if this is the correct implementation of circular queue using linked list.
Here is the code that i wrote
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
} *rear,*front,*temp,*newNode;
void create()
{
front = rear = NULL;
}
void enqueue(int data)
{
newNode = (struct node*) malloc(sizeof(struct node));
newNode -> data = data;
newNode -> next = NULL;
if(front == NULL)
front = rear = newNode;
else
{
rear -> next = newNode;
rear = newNode;
}
rear -> next = front;
}
int dequeue()
{
int x;
if (front == NULL)
{
return -1;
}
else if (front == rear)
{
x = front->data;
delete front;
front = rear = NULL;
}
else
{
node *temp = front;
x = temp -> data;
front = front -> next;
rear -> next = front;
delete temp;
}
return x;
}
int empty()
{
if(front == NULL)
{
return 1;
}
else
return 0;
}
void display()
{
node *temp = front;
printf("\nCIRCULAR QUEUE : ");
do
{
printf("%d ",temp->data);
temp = temp->next;
}while (temp != front);
}
int main()
{
int num,choice;
while(1)
{
printf("\n\nQUEUE OPERATIONS\n\n1.ENQUEUE\n2.DEQUEUE\n3.DISPLAY\n\n");
scanf("%d",&choice);
switch (choice)
{
case 1:
printf("\nEnter item : ");
scanf("%d",&num);
enqueue(num);
break;
case 2:
if(!(empty()))
printf("\nDequeued element : %d",dequeue());
else
printf("\nEMPTY QUEUE\n");
break;
case 3:
display();
break;
default: exit(0);
}}
return 0;
}
When i enqueue integers to the program it seems to run the queue program just fine. Then i dequeued 2 numbers and the first 2 numbers was deleted. Then i inserted 2 more numbers, but when i displayed the numbers, the recently inserted numbers got displayed in the back, not at the front.
Is there a solution? or is this just the correct implementation of circular queue using linked list?
This implementation is wrong.
Firstly, in the function dequeue(), you used delete front; and delete temp;.
This is an invaild syntax in C. Also, even if this code were C++, this is bad because the buffer is allocated via malloc(). You will have to use free(front); and free(temp); instead.
Secondly, you didn't check if the queue is empty in the display() function. Also the call of display() is not guarded with empty() check unlike it is done for dequeue() function. NULL will be dereferenced and Segmentation Fault may happen when display() is called when the queue is empty.
Also note that you should check the return values of scanf() to check if it actually read data (or didn't read, reaching at EOF or invalid input) and casting result of malloc() is discouraged.

Unusual Seg Fault: Cannot declare variables outside global?

I've been stuck for a few hours working on a c program that will loop 5 times while the user inputs 5 integers for a linked list. Somehow I cannot declare variables in my main without getting a segmentation fault in the print function.
My typedef:
typedef struct node_{
int value;
struct node_* next;
}node;
int y = 0; //If this is made local in main, seg fault
My main
int main(void)
{
node *head;
int x;
//int y; /*Does not work here*/
while(y < 5)
{
printf("Insert: ");
scanf("%d", &x);
head = insert_top(head, x);
print(head);
y ++;
}
free(head);
return 0;
}
My insert function
node* insert_top(node* head, int value)
{
node *newHead;
newHead = malloc(sizeof(node));
newHead->value = value;
if(head == NULL)
{
head = newHead;
head->next = NULL;
return head;
}
else
{
newHead->next = head;
head = newHead;
return head;
}
}
My print function
void print(node* head)
{
if(head == NULL)
{
printf("List is empty\n");
return;
}
else
{
while(head != NULL)
{
printf("%d->", head->value);
head = head->next;
}
printf("NULL\n");
}
}
For some reason, if I set the program to loop until the user inputs a number, say, -1, the program is fine and no problem. But I cannot declare any other integers (even if they have no use) without getting a seg fault. Can anyone help me figure out why this is happening and what I can do to fix it? I would like to be led down the path, but not necessarily told the answer.
node *head = NULL;
int y = 0; /*Does not work here*/
Please make above change in main and remove global declaration of y.

linked list with function

I'm trying to create a program which creates and display linked list.
Now i'm having trouble with my create_list() function, it doesn't create any list.
What i'm doing wrong ?
Sorry for bad english :/
CODE :
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} node;
int main(){
node *start;
start = NULL;
int a,n,on = 1;
while(on == 1){
printf(" \n choose: \n 1 --- create list \n 2 --- display list \n");
scanf("%d",&n);
switch(n){
case 1:
printf("-------------------------------------------- \n");
printf(" Enter the elements. The last element is 0 \n");
printf("-------------------------------------------- \n");
Create_list();
Display_list(start);
break;
case 2:
Display_list(start);
break;
}
}
system("pause");
return 0;
}
void Display_list(node *curr){
if(curr){
while (curr->next != NULL){
printf("%d \n",curr->data);
curr=curr->next;
}
} else {
printf(" \n The list is not created ! \n");
}
}
void Create_list(node *curr){
int i;
node *start = NULL;
if (start == NULL){
curr = (node *)malloc(sizeof(node));
start=curr;
while ( i != 0){
scanf("%d",&i);
if(i == 0){
curr->next=NULL;
curr=start;
} else {
curr->data=i;
curr->next=(node *)malloc(sizeof(node));
curr=curr->next;
}
}
} else {
printf(" \n list already exists ! \n");
}
}
The function Create_List(node *curr) needs some arguments. You are not passing any arguments from main(). Did your code compile?
The function Create_List(node *curr) needs some arguments. You are not passing any arguments from main(). Did your code compile?
What you should do is take a node in main which will store location of first node of the linked list.
void Insert(struct node **q, int num) //Num is the data to be added and **q is the pointer to the first node of the list.
{
struct node *temp, *r;
temp = *q;
if (*q == NULL) {
temp = ((struct node *)malloc(sizeof(struct node)));
temp->data = num;
temp->link = NULL;
*q = temp;
}
else {
while (temp->link != NULL)
temp = temp->link;
r = ((struct node *)malloc(sizeof(struct node)));
r->data = num;
r->link = NULL;
temp->link = r;
}
}
The start in Create_list is not related to the start in main. Since both are local to their respective functions, one can't even see the other. So setting start doesn't actually set start, if you will. :P
You'll need to either bring start outside of the functions and make it global, or pass &start (as a node**) from main into Create_list and modify *start to set the list head. (The latter is generally preferable, as globals are often trouble waiting to happen.)

Insertion into linked list

I wrote a program that inserts nodes into a linked list in descending order.But whenever I test my code with numbers 12,14,13,19,7 in this order.Whenever I entered 7 I took 7 is already in the list.But as easily seen 7 is not in the list before I inserted.After give this error,if I choose print option by typing 2 my program entered in an infinite loop.I can not see my mistake and I am very confused.
#include <stdio.h>
#include <stdlib.h>
struct node {
int content;
struct node* nextLink;
};
typedef struct node NODE;
void print (NODE*);
int insertNode (NODE** head, int x);
int main (void)
{
int num, choice;
NODE* head;
head = NULL;
do {
printf("\nPlease press 1 to insert or press 2 to print or press 0 to exit\n");
scanf("%d", &choice);
switch (choice) {
case 0:
return 0;
break;
case 1:
printf("Enter an integer to insert into the linkedlist: ");
printf("\n");
scanf("%d", &num);
insertNode(&head, num);
break;
case 2:
print(head);
break;
default:
printf("You entered an invalid number\n");
return 0;
break;
}
} while (choice == 1 || choice == 2);
return 0;
}
int insertNode (NODE** head, int i)
{
NODE* newNode;
newNode = (NODE*)malloc(sizeof(NODE));
newNode->content = i;
NODE* temporary = *head;
newNode->nextLink = NULL;
if ((*head == NULL) || ((*head)->content) < i) {
*head = newNode;
(*head)->nextLink = temporary;
}
else {
do {
if (((temporary->content) > i) && ((temporary->nextLink->content) < i)) {
newNode->nextLink = temporary->nextLink;
temporary->nextLink = newNode;
return;
}
else if (temporary->content == i) {
printf("To be inserted value is already in the list\n");
return;
}
temporary = temporary->nextLink;
} while (temporary->nextLink != NULL);
if (temporary->content == i) {
printf("To be inserted value is already in the list\n");
return;
}
temporary->nextLink = newNode;
}
return 0;
}
void print (NODE* head)
{
if (head == NULL) {
printf("\nLinkedList is empty \n");
}
while (head != NULL) {
printf("%d ", head->content);
head = head->nextLink;
}
}
I compiled it and ran it and it seemed to work fine except for one thing. insertNode is defined to return an int, yet 3 of the return statements are void returns. To get it to compile, I changed them to return 0;. If you were able to compile and run it as is, then it could be the stack was getting destroyed by the inconsistent returns.
Your code won't work, if the first two values to be inserted are in descending order. It would give segmentation fault.
For the insertion of 2nd element you need to be careful
So after if condition
else if (temporary->content > i && temporary->nextLink==NULL)
(*head)->nextLink = newNode;
Your code is doing too much. If you code it differently, there are no special cases (such as insert at the top, insert at the tail of the list).
int insertNode (NODE **head, int val)
{
NODE *newnode;
for ( ; *head; head = &(*head)->nextLink) {
if ( (*head)->content == val) {
printf("To be inserted value (%d)is already in the list\n", val);
return 0;
}
if ( (*head)->content > val) break;
}
newnode = malloc(sizeof *newnode); // Maybe check return here ;-)
newnode->content = val;
newnode->nextLink = *head;
*head = newnode;
return 1;
}

Resources