Reputation: 5681
I am creating a list with 3 elements but when I print the list , it shows an extra zero element.I can't figure where this comes from.
#include <stdlib.h>
#include <stdio.h>
typedef struct node
{
int data;
struct node *next;
} node;
void Push(struct node **head, int data)
{
struct node *newNode = (struct node*) malloc(sizeof(struct node));
newNode-> data = data;
newNode-> next = *head;
*head = newNode;
}
void createList(struct node **head)
{
Push(head, 1);
Push(head, 2);
Push(head, 3);
}
void printList(struct node *head)
{
struct node *ptr = head;
while(ptr != NULL)
{
printf("%d \n", ptr-> data);
ptr = ptr-> next;
}
return;
}
int main() {
struct node *head = NULL;
head = (struct node*) malloc(sizeof(struct node));
createList(&head);
printList(head);
printf("\n");
return 0;
}
Output:
3
2
1
0
Upvotes: 0
Views: 304
Reputation: 1163
You have four nodes in your list: the original that you malloc in "main()” plus the three added via "Push" in "createList". Presumably the data in the extra one is zero because you haven’t set it in main (although I’d expect it to be gibberish since it’s allocated memory but not cleared).
Upvotes: 0
Reputation: 170064
It's actually displaying an indeterminate value. Because right here:
head = (struct node*) malloc(sizeof(struct node));
Is where you create the first real node, which everything is inserted before. You are (un)lucky the run-time is zeroing out the memory for you. Because that's the only thing stopping you from accessing some random address. In general, the content of the memory returned from malloc
is indeterminate.
Remove that line and you'll see only the items added by createList
. Plus your program will be with well defined behavior.
Upvotes: 2