如何在C中正确释放char **表 [英] how to properly free a char **table in C
问题描述
我需要您对这段代码的建议: 表字段options [0],options [1]等...似乎没有正确释放. 感谢您的回答
I need your advice on this piece of code: the table fields options[0], options[1] etc... doesn't seem to be freed correctly. Thanks for your answers
int main()
{
....
char **options;
options = generate_fields(user_input);
for(i = 0; i < sizeof(options) / sizeof(options[0]); i++) {
free(options[i]);
options[i] = NULL;
}
free(options);
}
char ** generate_fields(char *)
{
char ** options = malloc(256*sizeof(char *));
...
return options;
}
推荐答案
问题是这样的:
for(i = 0; i < sizeof(options) / sizeof(options[0]); i++)
options
是指针类型,而不是数组类型,因此sizeof(options)
将始终相同(在32位计算机上通常为4个字节,在64位计算机上通常为8个字节),因此sizeof(options)/sizeof(options[0])
几乎总是1.
options
is a pointer type, not an array type, so sizeof(options)
will always be the same (typically 4 bytes on a 32-bit machine or 8 bytes on a 64-bit machine), so sizeof(options)/sizeof(options[0])
will almost always be 1.
关键是要始终按与malloc
相同的方式存储free
内存.因此,如果先malloc
二维数组,然后malloc
一系列一维数组,则在释放它时需要做相反的操作:
The key is to always free
memory in the same manner as you malloc
'ed it. So, if you malloc
a 2-dimensional array and then malloc
a series of 1-dimensional arrays, you need to do the reverse when freeing it:
char ** generate_fields(char *)
{
char ** options = malloc(256*sizeof(char *));
for(int i = 0; i < 256; i++)
options[i] = malloc(some_size);
return options;
}
void free_fields(char ** options)
{
for(int i = 0; i < 256; i++)
free(options[i]);
free(options);
}
请注意,如果大小(在这种情况下为256)不是常数,则您需要自己对其进行跟踪,因为否则,您将无法知道释放时要循环多少次.
Note that if the size (256 in this case) is not a constant, you need to keep track of it yourself, since otherwise you have no way of knowing how many times to loop when freeing.
这篇关于如何在C中正确释放char **表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!