解码 Valgrind 的输出

Decoding output from Valgrind

我试图理解 Valgrind 执行后的输出,如下所示:

valgrind --leak-check=yes "someprogram"

输出在这里:

==30347==
==30347== HEAP SUMMARY:
==30347==     in use at exit: 126,188 bytes in 2,777 blocks
==30347==   total heap usage: 4,562 allocs, 1,785 frees, 974,922 bytes
        allocated
==30347==
==30347== LEAK SUMMARY:
==30347==    definitely lost: 0 bytes in 0 blocks
==30347==    indirectly lost: 0 bytes in 0 blocks
==30347==      possibly lost: 0 bytes in 0 blocks
==30347==    still reachable: 126,188 bytes in 2,777 blocks
==30347==         suppressed: 0 bytes in 0 blocks
==30347== Reachable blocks (those to which a pointer was found) are
          not shown.
==30347== To see them, rerun with: --leak-check=full --show-reachable=yes
==30347==
==30347== For counts of detected and suppressed errors, rerun with: -v
==30347== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

根据输出,没有丢失字节,但似乎有仍可访问 块。那么我有内存泄漏吗?

没有

您最关心的是无法访问的块。您在这里看到的是,在可访问的内存块中仍有 "pointing" 的活动变量。它们仍在范围内。

例如,无法访问的块是您动态分配的内存,使用了一段时间,然后即使程序仍在执行,对它的所有引用都超出了范围。由于您不再有任何指向它们的句柄,因此它们现在不可恢复,从而造成内存泄漏。

这里引用 Valgrind 文档:

"still reachable" means your program is probably ok -- it didn't free some memory it could have. This is quite common and often reasonable. Don't use --show-reachable=yes if you don't want to see these reports.