谭浩强C语言教材中的例题疑惑。。求救!!!

来源:百度知道 编辑:UC知道 时间:2024/06/05 15:38:18
我突然间对谭浩强C语言教材中的例题产生了疑惑:疑惑是既然create函数中的p1和p2都是局部变量,调用完后就释放空间了,那为什么返回的头指针其后面的节点还存在呢?请大虾指教!!!
#include<stdio.h>
#define NULL 0
#define LEN sizeof(struct student)
struct student
{
long num;
float score;
struct student *next;
};
int n;
struct student *create(void)
{
struct student *head;
struct student *p1,*p2;
n=0;
p1=p2=(struct student*)malloc(LEN);
scanf("%ld,%f",&p1->num,&p1->score);
head=NULL;
while(p1->num!=0)
{
n=n+1;
if(n==1) head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct student*)malloc(LEN);
scanf("%ld,%f",&p1->num,&p1->score);
}
p2->next=NULL;
return head;
}
void main()
{
struct student *p;
p=create();
while(p!=NULL)
{
printf("%d %f ",p->num,p->score);
p=p->next;
}
}

我的问题是你在create里看到free了吗?malloc是在堆上分配内存,不调用free,内存就没有释放,你把分配的内存地址给谁是你的问题。明白吗?

呵呵.是这样的.p=create(); 这里,调用时该函数时,创建了一个链表,就是一个结点,不是吗?这些结点的地址是通过申请调用的.系统分配时,不是在动态区的,关键是这一点.知道吗?所以当函数调用结束时,它们是存在的.返回的地址是有效的.朋友.

空间并没有被释放,还在内存里,只是你无法再用它的名称了。想要释放的话用free()函数

malloc函数分配的内存只有显式调用free才会释放掉。