Reputation: 5
I don't know what is wrong with this code. when I "display" items that I entered from the "ADD", there are many unnecessary items being displayed. Why is this happening?
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
struct list
{
char name[20];
int age;
char gender[10];
struct list *next;
};
void main(void)
{
struct list *HEAD = NULL;
struct list *temp, *trav;
char choice;
while(1)
{
clrscr();
printf("MENU\n");
printf("A) ADD\n");
printf("B) DISPLAY\n");
printf("X) EXIT\n");
scanf("%c", &choice);
switch(toupper(choice))
{
case 'A':
temp= (struct list*)malloc(sizeof(struct list));
printf("Fill-Up the following:\n");
printf("Name:");
fflush(stdin);
gets(temp->name);
printf("Age:");
fflush(stdin);
scanf("%d",&temp->age);
printf("Gender:");
fflush(stdin);
gets(temp->gender);
if(HEAD == NULL)
{
HEAD = temp;
}
else if(HEAD!=NULL)
{
for(trav=HEAD; trav->next != NULL; trav= trav->next);
trav->next=temp;
}
else
{
printf("Not Enough Memory!\n");
}
break;
case 'B':
if(HEAD==NULL)
{
printf("Linked List is Empty!\n");
getch();
break;
}
if(HEAD!=NULL){
for(trav=HEAD; trav != NULL; trav=trav->next )
{
printf("Name: %s\n", trav->name);
printf("Age: %d\n", trav->age);
printf("Gender: %s\n", trav->gender);
getch();
}
}
break;
case 'X':
free(HEAD);
free(trav);
free(temp);
exit(1);
break;
}
}
}
Upvotes: 0
Views: 130
Reputation: 12179
You are initializing temp like this:
temp= (struct list*)malloc(sizeof(struct list));
But you never initialize the values of your structure. So they contain garbage. All malloc() does is return a chunk of memory to you from the Heap. You are responsible for its care and feeding, so set all the data members to known values, such as NULL, etc.
This is very evident if you use a debugger, and examine the value of temp after the mallloc() assignment (see image).
So, the take-away is to always initialize the data members of your malloc'd structure.
Upvotes: 2