【发布时间】:2018-08-19 10:42:46
【问题描述】:
我使用双向链表在 C++ 中实现 Deque。
析构函数:
Deque::~Deque()
{
while (this->left_p)
{
node *temp = this->left_p;
this->left_p = this->left_p->next;
delete temp;
}
this->right_p = NULL;
}
当我使用valgrind --leak-check=full ./a.out 来检查内存泄漏只是为了测试我的析构函数时,我得到了以下输出:
==2636==
==2636== HEAP SUMMARY:
==2636== in use at exit: 72,704 bytes in 1 blocks
==2636== total heap usage: 1,003 allocs, 1,002 frees, 97,760 bytes allocated
==2636==
==2636== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1
==2636== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2636== by 0x4EC3EFF: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==2636== by 0x40106B9: call_init.part.0 (dl-init.c:72)
==2636== by 0x40107CA: call_init (dl-init.c:30)
==2636== by 0x40107CA: _dl_init (dl-init.c:120)
==2636== by 0x4000C69: ??? (in /lib/x86_64-linux-gnu/ld-2.23.so)
==2636==
==2636== LEAK SUMMARY:
==2636== definitely lost: 0 bytes in 0 blocks
==2636== indirectly lost: 0 bytes in 0 blocks
==2636== possibly lost: 0 bytes in 0 blocks
==2636== still reachable: 72,704 bytes in 1 blocks
==2636== suppressed: 0 bytes in 0 blocks
==2636==
==2636== For counts of detected and suppressed errors, rerun with: -v
==2636== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
我不明白为什么 1003 个分配器中仍有一个不是空闲的。
为什么我有一个内存泄漏?我的析构函数有什么问题?
在这里测试代码:
/* Deque Test Program 6 */
#include <cstring>
#include <iostream>
#include "Deque.h"
using namespace std ;
int main (int argc, char * const argv[]) {
cout << "\n\nDeque Class Test Program 6 - START\n\n";
// Make a Deque
Deque * dq1 = new Deque();
for( int i = 0 ; i<1 ; i++ ){
dq1->push_left(1);
// dq1->display();
}
cout << "Size=" << dq1->size() << endl ;
// The destructor should delete all the nodes.
delete dq1 ;
cout << "\n\nDeque Class Test Program 6 - DONE\n\n";
return 0;
}
编辑:删除实现代码。
【问题讨论】:
-
请提取一个 MCVE 并将其放入您的问题中。外部链接太不稳定,而且往往会发生变化。
-
如果没有 Deque.cpp 的知识,就无法判断这里出了什么问题。
-
@Rudi 对不起。更新了我的问题
-
我无法重现该错误。要么你在本地修改了一些东西,要么你在 C 标准库中遇到了一个错误。当您使用 valgrind 时,您还应该使用
-g开关编译和链接所有程序,因为 valgrind 在可以找到调试信息时会提供更好的输出。 (作为旁注,我还建议在将 .cpp 转换为 .o 时删除显式的g++ -c调用,因为 make 有一个针对这种情况的内置规则。) -
删除左侧的所有节点后,继续设置
this->right_p = NULL;。在我看来不是很谨慎。
标签: c++ algorithm valgrind deque