Valgrind 抑制错误... Grrr

Valgrind Suppressed Errors... Grrr

我知道很多人并不认为 "still reachable" 内存泄漏是真正的内存泄漏。但是,我试图让 Valgrind 在错误为 "still reachable" 时报告错误。更具体地说,这是我当前的输出:

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)

两个被抑制的错误来自 "still reachable" 个错误。我希望这些被认为是正确的错误,以便程序 returns 一个错误代码。

The two suppressed errors are coming from "still reachable" errors.

几乎可以肯定不会。在程序退出时执行的泄漏检查的结果在很大程度上与程序运行时执行的错误内存访问分析分开。您可以使用虚拟程序进行测试,例如 still-reachable 内存不会产生抑制错误:

#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 个字节仍可到达,并且存在 抑制(或未抑制)错误。

I would like these to be considered proper errors so that the program returns an error code.

压制的目的是忽略已知的,believed-harmless 错误行为,通常是系统库。尽管您可以编写自己的抑制文件,但默认情况下您获得的抑制来自您无法控制的组件。

在各种泄漏的情况下以错误代码退出是完全不同的事情。您在评论中写道,您是 运行 您的 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 退出。