[英]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?
I have a function that takes a pointer to a char ** and fills it with strings (an array of strings I guess). 我有一个函数,该函数需要一个指向char **的指针,并用字符串(我猜是字符串数组)填充它。 *list_of_strings* is allocated memory inside the function.
* 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? */
How would I go about freeing the memory after I've used the strings? 使用完字符串后,如何释放内存? If I call
如果我打电话
free(list_of_strings);
won't that just free the actual pointers and not the memory each string itself was using? 那不只是释放实际的指针,而不是释放每个字符串本身正在使用的内存吗? How do I completely free the memory
我如何完全释放内存
Just for clarity the function looks something like this: 为了清楚起见,该函数如下所示:
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
}
/* ... */
}
won't that just free the actual pointers and not the memory each string itself was using?
那不只是释放实际的指针,而不是释放每个字符串本身正在使用的内存吗?
Yes, indeed. 确实是的。
How do I completely free the memory
我如何完全释放内存
By looping through the array and freeing each string one by one before freeing up the array itself. 通过遍历数组并在释放数组本身之前一一释放每个字符串。 Eg
例如
for (i = 0; i < SOMETHING; i++) {
free(list[i]);
}
free(list);
Basically, there's a rule of thumb to allocating and freeing: You need to call as many free() as you called malloc(). 基本上,分配和释放有一个经验法则:您需要调用与调用malloc()一样多的free()。 It's as simple as that.
就这么简单。 In every other case you got yourself a memory leak.
在其他所有情况下,您都会遇到内存泄漏。
Yes, you have to free()
every block you obtained from malloc()
. 是的,您必须
free()
从malloc()
获得的每个块的free()
malloc()
。 You do it by traversing the array of pointers and caling free()
on each element and only then freeing the array itself. 您可以通过遍历指针数组并在每个元素上校准
free()
,然后释放数组本身来做到这一点。
Only you know that there's a tree-like structure that could be freed recursively, that knowledge is not anywhere in the C runtime heap, so the heap manager has no idea about that and your program has to free everything itself. 只有您知道存在可以递归释放的树状结构,C运行时堆中没有知识,因此堆管理器对此一无所知,您的程序必须释放所有内容。
You need to iterate over list
and call free()
on every array member. 您需要遍历
list
并在每个数组成员上调用free()
。 Then free the array. 然后释放数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.