Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

#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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading