c - malloc 之后的空闲内存分配

标签 c malloc free

我正在阅读 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",&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;
}

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

相关文章:

c - 函数内的 malloc char*,valgrind 报告内存泄漏

c - 在带有多个 malloc() 的二维数组的指针上使用 free() 吗?

c - 4 位值的按位循环右移

c - 具有指向彼此的指针的 Typedef 结构

将编译时断言作为表达式的一部分但不包含 _Static_assert

c - 地址未被堆叠、分配或(最近)释放

c - G-WAN 类似物

c - 具有二维数组 malloc 的结构

c - 当我尝试将结构添加到其他结构并使用 free 函数时出现问题

Delphi:如何释放动态创建的对象作为方法的参数