为什么 valgrind 没有检测到由于 realloc 而导致的这种可能的内存泄漏?

Why doesn't valgrind detect this possible memory leak due to realloc?

我不明白为什么 valgrind(3.14 版)在这个程序中没有检测到可能的内存泄漏:

#include <stdlib.h>

int main() {
  int *p = malloc(sizeof(int));
  p = realloc(p, 2 * sizeof(int));

  free(p);

  return 0;
}

C99 标准(ISO/IEC 9899:1999,第 314 页)对 realloc 说:

If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged. [...] The realloc function returns a pointer to the new object (which may have the same value as a pointer to the old object), or a null pointer if the new object could not be allocated.

所以可能会出现pNULL但是之前用malloc分配的内存单元还在,这应该不会是内存泄漏吧?

如果我用 gcc -std=c99 编译程序并用 --tool=memcheck --leak-check=full --track-origins=yes 执行 valgrind,它会给出以下消息:

==313618== Memcheck, a memory error detector
==313618== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==313618== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==313618== Command: ./a.out
==313618== 
==313618== 
==313618== HEAP SUMMARY:
==313618==     in use at exit: 0 bytes in 0 blocks
==313618==   total heap usage: 2 allocs, 2 frees, 12 bytes allocated
==313618== 
==313618== All heap blocks were freed -- no leaks are possible
==313618== 
==313618== For counts of detected and suppressed errors, rerun with: -v
==313618== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Valgrind 不会分析您的代码;它会分析您的代码所采取的操作。

在这个特定的 运行 realloc 中没有失败,所以没有内存泄漏,所以 valgrind 没有什么可报告的:

All heap blocks were freed

这就是 valgrind 所知道的。

要检测代码中的问题,您需要静态代码分析工具。