我构建了一个链表库,并编写了一个清除函数,该函数遍历列表并释放与列表相关的所有内存。像这样:
/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 时,它会说“间接丢失:5 个 block 中的 120 个字节”,这是我添加到列表中的节点数。 我的问题是如何释放我使用的这些内存位置?
谢谢
最佳答案
"indirectly lost" means your program is leaking memory in a pointer-based structure.
换句话说,这表明您的链表节点有另一个指针,您已将其设置为 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;
}
关于c - 使用 valgrind 修复内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24762559/