[英]Cannot Free Memory in C - Dynamic Struct and array
在過去的兩天里,我一直在嘗試釋放程序的內存。 由於某些原因,我永遠無法完全自由。 我有一個循環,它在其中兩次分配malloc:
struct entry
{
int utf8length;
char * utf8text;
};
for( int i = 0; i < constant_pool_count; i++ )
{
ent = malloc(sizeof(struct entry));
if(ent==NULL)
{
fprintf(stderr, "Failed malloc, Exiting the program \n");
exit(-1);
}
ent->utf8length = sizeOfUtf;
carr = malloc(sizeof(char) * sizeOfUtf + 1);
if(carr==NULL)
{
fprintf(stderr, "Failed malloc, Exiting the program \n");
exit(-1);
}
//More code
}
我應該如何釋放它們?
在此片段之后的代碼中,您可能具有:
ent->utf8text = carr;
您將分兩個步驟釋放每個struct entry
:
free(ent->utf8text);
free(ent);
請注意,此代碼略有不一致: malloc(sizeof(char) * sizeOfUtf + 1);
。 大小是正確的,因為sizeof(char)
為1
,但是為了保持一致,它應該讀為:
malloc(sizeof(char) * (sizeOfUtf + 1));
要么
malloc(sizeOfUtf + 1);
第一種情況,它們在循環中被釋放:
struct entry
{
int utf8length;
char * utf8text;
};
...
for( int i = 0; i < constant_pool_count; i++ )
{
struct entry * ent;
char * carr;
ent = malloc(sizeof(struct entry));
if(ent==NULL)
{
fprintf(stderr, "Failed malloc, Exiting the program \n");
exit(-1);
}
ent->utf8length = sizeOfUtf;
carr = malloc(sizeof(char) * sizeOfUtf + 1);
if(carr==NULL)
{
fprintf(stderr, "Failed malloc, Exiting the program \n");
exit(-1);
}
ent->utf8text = carr; // I suppose
//More code
free(ent->utf8text);
free(ent);
}
第二種情況,您需要使它們脫離循環,然后釋放它們
struct entry
{
int utf8length;
char * utf8text;
};
...
struct entry * all[constant_pool_count];
for( int i = 0; i < constant_pool_count; i++ )
{
struct entry * ent;
char * carr;
ent = malloc(sizeof(struct entry));
if(ent==NULL)
{
fprintf(stderr, "Failed malloc, Exiting the program \n");
exit(-1);
}
ent->utf8length = sizeOfUtf;
carr = malloc(sizeof(char) * sizeOfUtf + 1);
if(carr==NULL)
{
fprintf(stderr, "Failed malloc, Exiting the program \n");
exit(-1);
}
ent->utf8text = carr; // I suppose
all[i] = ent;
//More code
}
... some code
// free them
for( int i = 0; i < constant_pool_count; i++ )
{
free (all[i]->utf8text);
free (all[i]);
// may be "all[i] = NULL;" if useful ?
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.