![](/img/trans.png)
[英]How can I free an array of pointers where each pointer points to an address of a string which I allocated inside of a function?
[英]Freeing memory which has been allocated to an array of char pointers (strings). Do I have to free each string or just the “main” pointer?
我有一个函数,该函数需要一个指向char **的指针,并用字符串(我猜是字符串数组)填充它。 * list_of_strings *是在函数内部分配的内存。
char * *list_of_strings = NULL;
/* list_of_strings malloc'd inside function */
fill_strings_with_stuff(&list_of strings);
use_list_for_something(list_of_strings);
/* Now how do I free it all? */
使用完字符串后,如何释放内存? 如果我打电话
free(list_of_strings);
那不只是释放实际的指针,而不是释放每个字符串本身正在使用的内存吗? 我如何完全释放内存
为了清楚起见,该函数如下所示:
fill_strings_with_stuff(char *** list)
{
*list = malloc(AMOUNT);
for (i = 0; i < SOMETHING; i++) {
*(list + i) = malloc(LINE_LEN);
*(list + i) = some_string_from_somewhere
}
/* ... */
}
那不只是释放实际的指针,而不是释放每个字符串本身正在使用的内存吗?
确实是的。
我如何完全释放内存
通过遍历数组并在释放数组本身之前一一释放每个字符串。 例如
for (i = 0; i < SOMETHING; i++) {
free(list[i]);
}
free(list);
基本上,分配和释放有一个经验法则:您需要调用与调用malloc()一样多的free()。 就这么简单。 在其他所有情况下,您都会遇到内存泄漏。
是的,您必须free()
从malloc()
获得的每个块的free()
malloc()
。 您可以通过遍历指针数组并在每个元素上校准free()
,然后释放数组本身来做到这一点。
只有您知道存在可以递归释放的树状结构,C运行时堆中没有知识,因此堆管理器对此一无所知,您的程序必须释放所有内容。
您需要遍历list
并在每个数组成员上调用free()
。 然后释放数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.