Ankur Varshney
Ankur Varshney

Reputation: 19

Why is this code stuck in an infinite loop?

Why is head is going to some random value?

// Simple insertion at the starting of link list  

#include<iostream>
using namespace std;
struct node{
    int d;
    node *next;
}; // creation of node

node *head=new node; // is there any problem?

void insert(int x)
{
    if (head==NULL) { // is there something wrong?
        head->d=x;
        haad->next=NULL;
    } else {
        node *t=new node;
        t->d=x;
        t->next=head;
        head=t;
    }
}

int main() {
    insert(1);           // function calling
    insert(2);           // function calling
    insert(3);           // function calling
    while(head!=NULL) {
        cout<<head->d<<" ";
        head=head->next;
    } // this is going on to infinity
    return 0;
}

This code is lopping till infinity and I am not able to understand why? Why is head going to some random value after 3 2 1? Is there any problem in declaring head globally?

Upvotes: 0

Views: 206

Answers (1)

SHG
SHG

Reputation: 2616

head is going to some random value because the last element in your list is pointing with next to a random value.

This last element is the first node you created in this line:

node *head=new node;

By doing that, you are allocating memory for this node on the heap, however, you're not setting any values to the node's fields, including next. Then in the loop, when head is pointing to the last node (that was allocated first) head->next is not NULL and therefore the loop continues.


Three side notes:

  1. Using head itself to iterate over the list elements is not a good idea since you're losing the pointer to the head of the list.
  2. head can be declared globally but usually you should have a good reason for that. In your program I'd define it in main() and pass it to the functions that need it.
  3. This code:

    if (head==NULL) { // is there something wrong?
        head->d=x;
        haad->next=NULL;
    

    doesn't make lots of sense: it will never run, and in case it will --> segmentation fault (because if head is NULL you cannot refer to its fields.

Hope it helps.

Upvotes: 2

Related Questions