在打印单链表时,在c程序执行结束时,显示文件已停止工作

在打印单链表时,在c程序执行结束时,显示文件已停止工作,c,C,我创建了一个单链表,并编写了一个方法来打印它。它已正确编译并运行,但在执行结束时,它显示list.exe(编译代码后生成的文件)已停止工作,windows正在检查解决方案,如下所示 清单c #include<stdio.h> #include<stdlib.h> struct List { int a; List *b; }; void PrintElement(List *); int main() { List *head,*temp

我创建了一个单链表,并编写了一个方法来打印它。它已正确编译并运行,但在执行结束时,它显示list.exe(编译代码后生成的文件)已停止工作,windows正在检查解决方案,如下所示

清单c

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


struct List
{
    int a;
    List *b;
};

void PrintElement(List *);

int main()
{
    List *head,*temp;
    int n,k;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        temp->b=(List*)malloc(sizeof(List));
        if(i==0)
        {
            temp=(List*)malloc(sizeof(List));
            head=temp;
        }
        else
        {
            temp=temp->b;
        }
        scanf("%d",&temp->a);


    }
    temp->b='\0';
    PrintElement(head);
    return(0);
}

void PrintElement(List *head)
{
    List *temp1=head;
    do
    {

    printf("%d\n",temp1->a);
    temp1=temp1->b;
   }
   while(temp1!='\0');
   free(temp1);
}
#包括
#包括
结构列表
{
INTA;
名单*b;
};
无效打印元素(列表*);
int main()
{
列表*标题,*温度;
int n,k;
scanf(“%d”和“&n”);
对于(inti=0;ib=(List*)malloc(sizeof(List));
如果(i==0)
{
temp=(列表*)malloc(sizeof(列表));
压头=温度;
}
其他的
{
温度=温度->b;
}
scanf(“%d”,&temp->a);
}
临时->b='\0';
打印元件(头部);
返回(0);
}
无效打印元素(列表*标题)
{
列表*temp1=头;
做
{
printf(“%d\n”,temp1->a);
temp1=temp1->b;
}
而(temp1!='\0');
免费(temp1);
}
有人能解释我做错了什么吗?

因为这句话,你的行为没有定义

temp->b=(List*)malloc(sizeof(List));
此时,您还没有初始化
temp
,需要在下面几行进行初始化

您也从不初始化“下一个”指针
b
指向
NULL
任意位置,因此当你遍历列表时,你将再次跳出列表,导致未定义的行为。雪上加霜的是,你试图
释放你从列表末尾走出来得到的节点。并且只释放内存,而不是实际的节点你分配


此外,标记字符串结尾的空字符和空指针之间也有明显的不同。大多数编译器将
'\0'
null
计算为相同的实际值,但它们仍然是不同的语义实体。

为什么
空闲(temp1)
在您的
PrintElement
函数(该函数应称为
PrintList
)的末尾?“有人能解释一下我做错了什么吗?”-在发布之前不要调试。不要发布屏幕截图。粘贴文本!