malloc 之后的空闲内存分配

free memory allocation after malloc

我正在阅读 Stephen Prata 的 "c primer plus"。链表有示例程序。程序使用malloc为结构体数组space分配内存,示例程序代码如下

#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]!='[=10=]')
{
    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",&current->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='[=10=]';
    else
        while(getchar()!='\n')
        continue;
}
return ret_val;
}

我的困惑来自内存释放代码。电流被释放 free(current); 为什么下面一行可以生效? 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);
}

免费(当前); 不清理当前@处的任何内存,只是把它还给内存池,所以它可以重复使用,没有清理内存,所以它会继续包含相同的数据 更好的做法是添加 当前=空; 就在

之后