[英]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.