Reputation: 7738
I have written a simple program to traverse through the nodes of a linked list.
struct node
{
int data;
struct node *next;
}*start;
start=(struct node *)malloc(sizeof(struct node));
start->next=NULL;
int main(void)
{
if(start==NULL)
{
printf("There are no elements in the list");
}
else
{
struct node *tmp;
printf("\nThe elemnets are ");
for(tmp=start;tmp!=NULL;tmp=tmp->next)
{
printf("%d\t",tmp->data);
}
}
return 0;
}
Whenever i am trying to print the elements of the linked list, however even though the list is empty, it gives the output
The elements are 5640144
What am i doing wrong ? Am i declaring the start pointer correctly ?
Why do i need to do this (actually i was not doing this initially, but was asked to by one of my friends)
start=(struct node *)malloc(sizeof(struct node));
start->next=NULL;
Upvotes: 3
Views: 5855
Reputation: 37970
Declaring a pointer to a node (start
) does not actually create the node itself - you need malloc()
to do this. However, malloc()
doesn't bother to fill the node with reasonable values, which is why you get a seemingly random value in data
. Try start->data = 42;
after start->next = NULL;
.
Edit: See ArjunShankar's comment about not calling malloc()
from outside a function.
Upvotes: 4
Reputation: 169
presently its may be giving you the garbage value for sure , present in the allocated memory block, as you have on assigned start->next = NULL; not assigned value to the data,
kindly use memset with 0, it will intialize memory block with zero for whole structure or intialize some value to the structure.
if you would have used gcc , it might not have raised this issue.I guess for this you wouldn't have.
struct is global, and start is an pointer to the structure, at the time of malloc, you have been alloted a structure size memory, initialized. if you have taken a global structure variable, you would not have faced such an issue, as its get initialized in bss.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
}*start;
int main(void)
{
start=(struct node *)malloc(sizeof(struct node));
start->next = NULL;
start->data = 100;
//memset(start,0,sizeof(struct node));
if(start==NULL)
{
printf("There are no elements in the list");
}
else
{
struct node *tmp;
printf("\nThe elemnets are ");
for(tmp=start;tmp!=NULL;tmp=tmp->next)
{
printf("%d\n",tmp->data);
}
}
return 0;
}
Upvotes: 1