To check a sample list imlpementation I tried the following code. But whenever i am trying to display the result it is getting inside a loop. I cant find where is it getting wrong.
#include<stdio.h>
#include<stdlib.h>
typedef struct linkedlist
{
int data;
struct linkedlist *next;
}node;
int main()
{
int ch,num;
node *head=NULL;
head=(node *)malloc(sizeof(node));
node *new=NULL;
new=(node *)malloc(sizeof(node));
node *temp=NULL;
temp=(node *)malloc(sizeof(node));
printf("\n1.Insert to list");
printf("\n3.Display the list");
printf("\n Enter Choice->");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("\n Enter data->");
scanf("%d",&num);
new->data=num;
new->next=NULL;
head->next=new;
break;
case 3: temp=head;
while(temp!=NULL)
{
printf("\n %d",temp->data);
temp=temp->next;
}
break;
default:printf("Wrong Choice");
break;
}
return 0;
}
There are two mistakes here.
case 3: temp=head;This is called a “memory leak.”I suggest that you study pointers a bit more; they seem to be confusing you.