我正在阅读 Stephen Prata 的“c primer plus”。链表有示例程序。程序使用malloc为结构体数组分配内存空间,示例程序代码如下。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TSIZE 45
struct film{
char title[TSIZE];
int rating;
struct film * next;
};
char * s_gets(char * st,int n);
int main(void)
{
struct film * head =NULL;
struct film * prev, * current;
char input[TSIZE];
puts("Enter first movie title:");
while(s_gets(input,TSIZE)!=NULL && input[0]!='\0')
{
current=(struct film *)malloc(sizeof(struct film));
if(head==NULL)
head=current;
else
prev->next=current;
current->next=NULL;
strcpy(current->title,input);
puts("Enter your rating <0-10>:");
scanf("%d",¤t->rating);
while(getchar()!='\n')
continue;
puts("Enter next movie title (empty line to stop):");
prev=current;
}
if(head==NULL)
printf("No data entered.\n");
else
printf("Here is the movie list:\n");
current=head;
while(current!=NULL)
{
printf("Movie: %s Rating: %d\n",current->title,current->rating);
current=current->next;
}
current=head;
while(current!=NULL)
{
free(current);
current=current->next;
}
printf("Bye!\n");
return 0;
}
char * s_gets(char * st,int n)
{
char * ret_val;
char * find;
if((ret_val=fgets(st,n,stdin)))
{
if((find=strchr(st,'\n'))!=NULL)
*find='\0';
else
while(getchar()!='\n')
continue;
}
return ret_val;
}
我的困惑来自内存自由代码。电流被释放
免费(当前);
为什么下面一行可以生效? current=current->next;
因为 current 被释放了,这一行应该没有办法访问当前的成员“next”。
期待您的帮助。
非常感谢。
最佳答案
当你这样做的时候
while(current!=NULL)
{
free(current);
current=current->next;
}
您使 current
指针悬空并尝试访问它 current=current->next;
这将导致未定义的行为。
我建议您按以下方式免费。
此外,您的 current
指针将指向 NULL
,因为您在自由 while 循环之前已经循环到列表末尾。
current=head;
while(current!=NULL)
{
struct film * temp = current;
current=current->next;
free(temp);
}
关于c - malloc 之后的空闲内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52005858/