Home > other >  Why is my execution being stopped after printing a linked list?
Why is my execution being stopped after printing a linked list?

Time:03-10

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node* link;
};
typedef struct node NODE;
typedef struct node HEAD;

void main()
{
    NODE *head;

    NODE *node1;
    node1 = malloc(sizeof(NODE));
    node1->data = 6;
    node1->link = head;
    head = node1;

    NODE *node2;
    node2 = malloc(sizeof(NODE));
    node2->data = 7;
    node2->link = head;
    head = node2;
    NODE *ptr = head;
    while(ptr != NULL)
    {
        printf("%d->",ptr->data);  //printing of current node's data.
        ptr = ptr->link;           //<------here execution is being halted after printing 5 and 6

        if(ptr == NULL)
        {
            printf("NULL");
        }
        
    }
}

The output is

7->6->

But i need expected output as

7->6->NULL

Can you please look into the code and correct my code if necessary and also please explain why my execution is being halted after printing data and not executing the printf("NULL") statement

CodePudding user response:

Here:

node1->link = head;

At here, the pointer head is still uninitialized, that is neither a block of memory nor NULL. So the linked-list is actually looking like 7 -> 6 -> ???. Since its not NULL, it doesn't satisfy the ptr == NULL comparison though satisfies ptr != NULL, kept running the loop but couldn't access the members' data (since there isn't a thing to access), so it halted.

Try initializing struct node *head = NULL.

  • Related