我认识到许多人并不认为“仍然可以到达”的内存泄漏是真正的内存泄漏。但是,我试图让Valgrind在“仍然可以到达”错误时报告错误。更具体地说,这是我当前的输出:
HEAP SUMMARY:
in use at exit: 23,221,680 bytes in 25 blocks
total heap usage: 27 allocs, 2 frees, 23,222,816 bytes allocated
Searching for pointers to 25 not-freed blocks
Checked 49,347,544 bytes
672 bytes in 24 blocks are still reachable in loss record 1 of 2
at 0x4C29792: malloc (** DETAILS OMITTED **)
by 0x2011F54: (** DETAILS OMITTED **)
by 0x405C75: main (** DETAILS OMITTED **)
23,221,008 bytes in 1 blocks are still reachable in loss record 2 of 2
at 0x4C29792: malloc (** DETAILS OMITTED **)
by 0x2011F54: (** DETAILS OMITTED **)
by 0x21B34CC: (** DETAILS OMITTED **)
by 0x20125DF: (** DETAILS OMITTED **)
by 0x406D14: main (** DETAILS OMITTED **)
LEAK SUMMARY:
definitely lost: 0 bytes in 0 blocks
indirectly lost: 0 bytes in 0 blocks
possibly lost: 0 bytes in 0 blocks
still reachable: 23,221,680 bytes in 25 blocks
suppressed: 0 bytes in 0 blocks
ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
两个被抑制的错误来自“仍可到达”错误。我希望将这些视为适当的错误,以便程序返回错误代码。
答案 0 :(得分:1)
两个被抑制的错误来自“仍可到达”错误。
几乎可以肯定不会。在程序退出时执行泄漏检查的结果与在程序运行时执行的错误内存访问的分析在很大程度上是分开的。您可以使用这样的虚拟程序进行测试,即仍然可访问的内存不会产生抑制的错误:
#include <stdlib.h>
int main(void) {
void *p = malloc(8);
return (int) p;
}
我明白了
==22685== LEAK SUMMARY: ==22685== definitely lost: 0 bytes in 0 blocks ==22685== indirectly lost: 0 bytes in 0 blocks ==22685== possibly lost: 0 bytes in 0 blocks ==22685== still reachable: 8 bytes in 1 blocks ==22685== suppressed: 0 bytes in 0 blocks ==22685== ==22685== For counts of detected and suppressed errors, rerun with: -v ==22685== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
请注意,报告仍然可以访问8个字节,并且存在 零 个被抑制(或未被抑制)的错误。
我希望这些被认为是正确的错误,以便程序返回错误代码。
抑制的目的是忽略已知的,被认为无害的错误行为,通常是系统库的错误行为。尽管您可以编写自己的抑制文件,但是默认情况下,抑制是由不受控制的组件引起的。
在发生各种泄漏时,以错误代码退出是完全不同的事情。您在评论中写道,您正在像这样运行valgrind测试:
valgrind --leak-check=full --show-reachable=yes --show-leak-kinds=all --error-exitcode=1 \
--track-origins=yes --log-file=LOG_FILE_NAME -v EXECUTABLE_NAME
您提供的选项中明显缺少--errors-for-leak-kinds
,它与--show-leak-kinds
分开,默认为definite,possible
。组合--error-exitcode=1 --errors-for-leak-kinds=all
会使valgrind将所有类型的泄漏计数为错误,并在检测到程序退出时仍检测到任何已分配的内存时以状态1退出。