列出链表时无限循环

时间:2010-12-09 00:50:34

标签: c

问题出现在while循环中。我找不到什么是错的。

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

5 个答案:

答案 0 :(得分:5)

您永远不会将最后一个节点设置为null。把
temp->next = NULL;
 在for循环之后。

使用malloc分配节点时,值不会初始化为任何值。所以next指向记忆中的一些随机位置。

答案 1 :(得分:2)

您可能缺少列表构建循环中的最后一行:

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

答案 2 :(得分:1)

分配最后一个节点时,永远不会设置其next指针。由于它是未初始化的,它将包含该内存位置中已有的任何数据,这几乎肯定不是NULL。处理完while循环中的所有节点后,程序将取消引用此未初始化的指针并调用未定义的行为。

答案 3 :(得分:0)

您确定要编译C吗?

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

答案 4 :(得分:0)

这是因为while (temp)总是包含一个值。 确保最后一个节点指向NULL值,以便temp=temp->next;返回NULL并退出循环。