计算 valgrind 错误而不报告它们

Count valgrind errors without reporting them

我目前正在维护一个内存池。我最近向该池添加了 valgrind 函数调用,以使其更有用地检测通过使用所述池发生的 valgrind 错误。我想做的是编写一个单元测试来检查我对 valgrind 函数的调用是否正常工作。例如,

int main(void)
{
  int * test = pool_malloc(sizeof(*test)); // details not important
  *test = 3;
  pool_free(test); // details not important

  if (*test == 2)
  {
    printf("HERE");
  }

  assert(VALGRIND_COUNT_ERRORS == 1);
}

这段代码现在正确地给我一个无效的读取错误,而以前它不会,因为即使内存返回到池中,它实际上并不是 free-d。但是,我不能使用这个确切的代码,因为我们的单元测试框架假定任何 valgrind 错误都意味着测试失败,因此我的上述测试将失败。我试过使用 VALGRIND_DISABLE_ERROR_REPORTING,但这似乎不仅会禁用报告,还会禁用错误检查 - 即 VALGRIND_COUNT_ERRORS 现在 returns 0。我真正想要的是 VALGRIND_DISABLE_ERROR_REPORTING_BUT_KEEP_COUNTING_ERRORS_THAT_OCCUR - 是否存在类似的东西?有没有更好的方法来完成我想做的事情?

你可以做的是使用 valgrind 客户端请求 VALGRIND_COUNT_ERRORS。

valgrind.h等人说:

    ...
             /* Can be useful in regression testing suites -- eg. can
                 send Valgrind's output to /dev/null and still count
                 errors. */
              VG_USERREQ__COUNT_ERRORS = 0x1201,
    ...
    /* Counts the number of errors that have been recorded by a tool.  Nb:
       the tool must record the errors with VG_(maybe_record_error)() or
       VG_(unique_error)() for them to be counted. */

所以,像这样: valgrind --log-file=/dev/null your_program 将使 valgrind 错误报告给 /dev/null,然后 your_program 可以 如果错误计数不符合预期,则输出错误。