Mauricio
Mauricio

Reputation: 15

Infinite loop while listing linked list

The problem is on while loop. I couldn't find what's wrong.

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

typedef struct node {
        int data;
        node *next;
        };

int main(){
 node * root= (node *) malloc(sizeof(node));
 node * temp = root;
 for(int i=0;i<10;i++){
         temp->data=i*10;
         temp->next=(node *) malloc(sizeof(node));
         temp=temp->next;
         }     
 temp =root;
 while(temp){ //infinite loop
         printf("\n%d",temp->data);
         temp=temp->next;       
         }
         getch();
    return 0;
}    

Upvotes: 1

Views: 4282

Answers (5)

Neilvert Noval
Neilvert Noval

Reputation: 1695

this is because while (temp) always contains a value. Make sure your last node points to a NULL value so that temp=temp->next; will return NULL and exits the loop.

Upvotes: 0

pmg
pmg

Reputation: 108978

Are you sure you're compiling C?

In the for loop, initialize the next pointer to NULL.

for (int i = 0; i < 10; i++) {
    /* ... */
    temp->next = malloc(sizeof (node));
    assert(temp->next && "no memory"); /* easy test of malloc return value */
    temp->next->next = NULL;
    /* ... */
}

Upvotes: 0

Nick Meyer
Nick Meyer

Reputation: 40272

When you allocate the last node, you never set its next pointer. Since it is uninitialized, it will contain whatever data was already in that memory location, which is almost certainly not NULL. After you've processed all the nodes in the while loop, your program will dereference this uninitialized pointer and invoke undefined behavior.

Upvotes: 1

Caner
Caner

Reputation: 59168

You never set the last nodes next to null. Put
temp->next = NULL;
after the for loop.

When you allocate node with malloc, values are not initialized to anything. So next points to some random place in the memory.

Upvotes: 5

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84159

You are probably missing this last line in your list building loop:

    /* ... */
    temp->next = NULL;
}

Upvotes: 2

Related Questions