In addition to the points made by @JonathanLeffler, I see problems in this block of code:
if(mode==1)
{
insert=malloc(sizeof(struct data));
printf("Id: ");scanf("%d",&(insert->id));
printf("Age: ");scanf("%d",&(insert->age));
insert=insert->next;
}
First time you execute this block, you do the following:
- Create memory for a
struct data
and let insert
point to it.
- Fill up the data in the
struct data
.
- Make
insert
become insert->next
. But insert->next
was not initialized to anything before the statement. At the end of the statement insert
points to something completely unpredictable.
- You have lost track of the memory you allocated since nothing points to it.
Second time you execute this block, you do the following:
- Create memory for a
struct data
and let insert
point to it.
- Fill up the data in the
struct data
.
- Make
insert
become insert->next
. But insert->next
was not initialized to anything before the statement. At the end of the statement insert
points to something completely unpredictable.
- You have lost track of the memory you allocated since nothing points to it.
What happened here?
- You repeated the same process.
- You have lost track of the memory allocated by two calls to
malloc
.
insert
still points to something unpredictable.
This process repeats every time you execute that loop.
Here's what you can to to fix it.
if(mode==1)
{
// Allocate memory and let temp point
// to the allocated memory.
temp=malloc(sizeof(struct data));
// Fill up the data of the newly allocated memory.
printf("Id: ");scanf("%d",&(temp->id));
printf("Age: ");scanf("%d",&(temp->age));
// Make temp clean by making its next point to NULL.
temp->next = NULL;
// Now figure out where to link this newly allocated
// memory to the linked list.
// Assuming you initialize insert correctly...
if ( insert == NULL )
{
initial = insert = temp;
}
else
{
insert->next = temp;
insert = temp;
}
}
Hope that makes sense.