简体   繁体   English

列出链接列表时无限循环

[英]Infinite loop while listing linked list

The problem is on while loop. 问题在while循环上。 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. 您永远不会将最后一个节点设置为null。 Put
temp->next = NULL;
after the for loop. 在for循环之后。

When you allocate node with malloc, values are not initialized to anything. 使用malloc分配节点时,值不会初始化为任何值。 So next points to some random place in the memory. 因此, next指向内存中的某个随机位置。

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. 分配最后一个节点时,永远不会设置其next指针。 Since it is uninitialized, it will contain whatever data was already in that memory location, which is almost certainly not NULL. 由于未初始化,因此它将包含该内存位置中已经存在的任何数据,几乎可以肯定不是NULL。 After you've processed all the nodes in the while loop, your program will dereference this uninitialized pointer and invoke undefined behavior. while循环中处理完所有节点后,程序将取消引用此未初始化的指针并调用未定义的行为。

Are you sure you're compiling C ? 您确定要编译C吗?

In the for loop, initialize the next pointer to NULL. 在for循环中,将next指针初始化为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. 这是因为while (temp)始终包含一个值。 Make sure your last node points to a NULL value so that temp=temp->next; 确保最后一个节点指向NULL值,以便temp=temp->next; will return NULL and exits the loop. 将返回NULL并退出循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM