[英]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",¤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;
}
我的困惑來自於沒有內存的代碼。 電流由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.