简体   繁体   English

用valgrind修复内存泄漏

[英]fixing memory leak with valgrind

i built a linked list library and i wrote a clear function which go through the list and free all the memory associated with list. 我建立了一个链接列表库,并编写了一个清晰的函数,该函数遍历列表并释放与列表关联的所有内存。 like this: 像这样:

/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);

and then when i run the valgrind, it will say that "indirectly lost: 120 bytes in 5 blocks" and this is the number of nodes i added to the list. 然后当我运行valgrind时,它会说“间接丢失:120个字节,分为5个块”,这是我添加到列表中的节点数。 my question is how i can free these memory locations i used ? 我的问题是如何释放我曾经使用的这些内存位置?

Thanks 谢谢

According to valgrind documentation , 根据valgrind文档

"indirectly lost" means your program is leaking memory in a pointer-based structure. “间接丢失”表示您的程序正在基于指针的结构中泄漏内存。

In other words, this is an indication that your linked list node has another pointer that you have set to a result of malloc , and you have forgotten to de-allocate that memory. 换句话说,这表明您的链表节点还有另一个指针,您已将其设置为malloc的结果,而您忘记了取消分配该内存。

The fix would be to add free for the pointer inside the linked list node: 解决方法是为链接列表节点内的指针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