malloc之后的空闲内存分配

Mar*_*ang 1 c malloc free

我正在读斯蒂芬普拉塔的"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",&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='\0';
    else
        while(getchar()!='\n')
        continue;
}
return ret_val;
}
Run Code Online (Sandbox Code Playgroud)

我的困惑来自无记忆代码.free(current); 为什么以下行可以生效,释放电流 ?current=current->next;由于电流被释放,该线路无法访问当前的"下一个".

期待您的帮助.

非常感谢.

kir*_*dar 5

当你这样做

while(current!=NULL)
{
    free(current);
    current=current->next;
}
Run Code Online (Sandbox Code Playgroud)

你使current指针悬空,你试图访问它current=current->next;,这将导致未定义的行为.

我建议你自由如下.此外,您的current指针将指向,NULL因为您已经循环到列表的末尾之前到自由while循环.

current=head;
while(current!=NULL)
{
    struct film * temp = current;
    current=current->next;
    free(temp);
}
Run Code Online (Sandbox Code Playgroud)