簡體   English   中英

用valgrind修復內存泄漏

[英]fixing memory leak with valgrind

我建立了一個鏈接列表庫,並編寫了一個清晰的函數,該函數遍歷列表並釋放與列表關聯的所有內存。 像這樣:

/creating the list
list *myList = (list*) calloc(1, sizeof(list));

//lets try to add a node to the list
list_add_at (NULL, 0, (int*)100);
list_add_at (myList, 0, (int*)100);
list_add_at (myList, 1, (int*)200);
list_add_at (myList, 2, (int*)300);
list_add_at (myList, 3, (int*)400);
list_add_at (myList, 4, (int*)600);
list_add_at (myList, 5, (int*)800);

list_clear(myList);

然后當我運行valgrind時,它會說“間接丟失:120個字節,分為5個塊”,這是我添加到列表中的節點數。 我的問題是如何釋放我曾經使用的這些內存位置?

謝謝

根據valgrind文檔

“間接丟失”表示您的程序正在基於指針的結構中泄漏內存。

換句話說,這表明您的鏈表節點還有另一個指針,您已將其設置為malloc的結果,而您忘記了取消分配該內存。

解決方法是為鏈接列表節點內的指針free添加:

while ( temp != NULL ){
        list->head = temp->next;
        free(temp->allocated_ptr); // <<= Free the memory attached to the node
        free(temp);
        temp = list->head;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM