请问这段C程序是哪有问题

来源:百度知道 编辑:UC知道 时间:2024/06/06 09:55:28
请问下面这段c程序是哪有问题
#include<stdio.h>
#include<stdlib.h>

#define LEN sizeof(struct xuesheng);

struct xuesheng
{
long xuehao;
float chengji;
struct xuesheng *next;
};

int main(void)
{
struct xuesheng *p1,*p2,*head;
int n;
head=NULL;
p1=p2=(struct xuesheng *)malloc(LEN);
scanf("%ld %f",p1->xuehao,p2->chengji);
while(p1->xuehao!=0)
{
++n;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct xuesheng *)malloc(LEN);
scanf("%ld %f",p1->xuehao,p1->chengji);
}
p2->next=NULL;
return 0;
}

问题多多:
1、把此行#define LEN sizeof(struct xuesheng);末尾的分号去掉
2、变量n定义后并没有赋初始值,就进行了++n的操作
3、程序结束时,p1指向的结构是无效的,但没有释放分配的内存
4、这个以head开头的单向链表没有释放内存,内存泄露了。

建议:
1、head的赋值不必在循环中,在循环外赋值比较好
2、xuehao和chengji的读取,可以考虑先读取到普通变量中,在判断后再分配结构内存,建立新链表。