开发者

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;
}    


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.


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

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


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.


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;
    /* ... */
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜