繁体   English   中英

malloc之后的空闲内存分配

[英]free memory allocation after malloc

我正在阅读斯蒂芬·普拉塔(Stephen Prata)的“ cprimary 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;
}

我的困惑来自于没有内存的代码。 电流由free(current);释放free(current); 为什么以下几行可以生效? current=current->next; 由于释放了当前电流,因此该行应该无法访问当前成员“下一个”。

期待您的帮助。

非常感谢。

当你这样做

while(current!=NULL)
{
    free(current);
    current=current->next;
}

您使current指针悬空,然后尝试访问它current=current->next; 这将导致不确定的行为。

我建议您按照以下方式释放。 另外,由于您已经循环到列表的末尾,然后到达free while循环,因此您current指针将指向NULL

current=head;
while(current!=NULL)
{
    struct film * temp = current;
    current=current->next;
    free(temp);
}

自由(当前); 不会清除当前@的任何内存,只是将其返回给内存池,因此可以重用,不执行内存清理,因此它将继续包含相同的数据将加current = NULL; 刚过

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM