0

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 
George
  • 5,808
  • 15
  • 83
  • 160
  • 1
    Your list have four nodes. In `main` you create a new node and don't set `data` which has an undefined value. In your case 0, but it also could be -1232. Then you do 3 pushes and when you print your list, you get 4 lines. – Pablo Jan 04 '18 at 13:14
  • You should note that there is [no reason to cast the result of `malloc`](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – StoryTeller - Unslander Monica Jan 04 '18 at 13:16

2 Answers2

2

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.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • Ok, I understand, thanks.It was an unecessary line since I already use `struct node *newNode = (struct node*) malloc(sizeof(struct node));` in Push , right? – George Jan 04 '18 at 13:21
  • @George - That's correct. So long as you initialize `head` with `NULL`, your push function will leave the list in a correct state. – StoryTeller - Unslander Monica Jan 04 '18 at 13:22
0

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).

Pam
  • 1,146
  • 1
  • 14
  • 18