![](/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.