过去两天我一直在尝试释放程序的内存。由于某种原因,我永远无法完全自由。我有一个循环,它在其中进行两次 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;
您可以通过 2 个步骤释放每个结构条目
:
free(ent->utf8text);
free(ent);
请注意,此代码略有不一致:malloc(sizeof(char) * sizeOfUtf + 1);
。大小是正确的,因为 sizeof(char)
是 1
,但为了保持一致性,它应该读取:
malloc(sizeof(char) * (sizeOfUtf + 1));
或者
malloc(sizeOfUtf + 1);
关于无法释放 C 中的内存 - 动态结构和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55057672/