Valgrind没有报错,但并非所有的堆分配都已被释放。

4

使用 Valgrind 运行程序后,我得到了以下结果:

1    jscherman@jscherman:~/ClionProjects/algo2-t4-tries$ g++ Set.hpp tests.cpp DiccString.hpp && valgrind --leak-check=yes --show-leak-kinds=all ./a.out                      
2    ==6823== Memcheck, a memory error detector
3    ==6823== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
4    ==6823== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
5    ==6823== Command: ./a.out
6    ==6823== 
7    test_empty_dicc...ok
8    test_copy_constructor...ok
9    test_define_defined...ok
10    test_get..ok
11    test_remove...ok
12    test_remove_tiny...ok
13    test_keys...ok
14    ==6823== 
15    ==6823== HEAP SUMMARY:
16    ==6823==     in use at exit: 72,704 bytes in 1 blocks
17    ==6823==   total heap usage: 282 allocs, 281 frees, 275,300 bytes allocated
18    ==6823== 
19    ==6823== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1
20    ==6823==    at 0x4C2DC10: malloc (vg_replace_malloc.c:299)
21    ==6823==    by 0x4EC3EFF: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
22    ==6823==    by 0x40104E9: call_init.part.0 (dl-init.c:72)
23    ==6823==    by 0x40105FA: call_init (dl-init.c:30)
24    ==6823==    by 0x40105FA: _dl_init (dl-init.c:120)
25    ==6823==    by 0x4000CF9: ??? (in /lib/x86_64-linux-gnu/ld-2.23.so)
26    ==6823== 
27    ==6823== LEAK SUMMARY:
28    ==6823==    definitely lost: 0 bytes in 0 blocks
29    ==6823==    indirectly lost: 0 bytes in 0 blocks
30    ==6823==      possibly lost: 0 bytes in 0 blocks
31    ==6823==    still reachable: 72,704 bytes in 1 blocks
32    ==6823==         suppressed: 0 bytes in 0 blocks
33    ==6823== 
34    ==6823== For counts of detected and suppressed errors, rerun with: -v
35    ==6823== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

似乎输出的最后一行没有泄漏问题。然而,我们还有这行代码:
17    ==6823==   total heap usage: 282 allocs, 281 frees, 275,300 bytes allocated

为什么我的程序没有任何错误,但仍然有一些未被释放的分配?是我的程序出了问题还是Valgrind在幕后做了什么?


1
我不会在这里放置我的代码,因为没有泄漏——著名的最后一句话。你为什么那么确定你的程序没有内存泄漏? - PaulMcKenzie
2
那看起来像是静态初始化泄漏。我猜你不拥有 dl-init.c 代码,对吧?它可能只是运行时库的启动代码。顺便说一句,使用 valgrind 很棒。 - WhozCraig
@PaulMcKenzie 我并不是...我的意思是Valgrind说没有(就我理解的)。所以,基于这个前提,如果我有一个泄漏,那么它会被作为错误抛出(对吧?),我只是避免在这里放置一堆我认为对问题本身来说不必要的代码。 - jscherman
@WhozCraig 我在C++方面有点新手,所以我不知道那是什么。我可以假设我没有使用它吗?:P - jscherman
1
@jscherman的回答很好地描述了一次性动态C++运行时分配可能涉及的内容,以及如何通常抑制它们以跟踪您*真正关心的泄漏(即您的代码)。 - WhozCraig
1个回答

4
valgrind报告的回溯显示,涉及内存分配是由应用程序加载的其中一个共享库的初始化函数进行的,显然是C++库本身。
共享库通常会为各种数据片段进行一次性分配,但在卸载时不会明确地释放它们。
这并不构成您自己代码中的内存泄漏。
valgrind附带了一个已知此类分配的列表,称为“抑制列表”,旨在抑制有关这些已知一次性分配的报告。
但是,偶尔这些抑制列表会错过一两个分配。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接