为什么 Valgrind 在未释放 malloc 内存后不报告任何问题?

Why does Valgrind not report any issue after not freeing malloc'd memory?

我想弄清楚为什么 Valgrind 不发出任何警告,即使在下面的代码中 malloc 之后没有 free

#include "stdlib.h"
#include "string.h"

char* ptr;

int main (int argc, char *argv[]) {
    ptr = static_cast<char*>(malloc(5 * sizeof(char)));
    strcpy(ptr, "test");
}

是否有某种 "automatic free" 我不知道或者我遗漏了什么?

谢谢。

它确实报告了问题,但要查看它,您需要 运行 Valgrind 和 --leak-check=full --show-leak-kinds=all 选项:

$ valgrind --leak-check=full --show-leak-kinds=all ./a.out
==317235== Memcheck, a memory error detector
==317235== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==317235== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==317235== Command: ./a.out
==317235== 
==317235== 
==317235== HEAP SUMMARY:
==317235==     in use at exit: 5 bytes in 1 blocks
==317235==   total heap usage: 2 allocs, 1 frees, 72,709 bytes allocated
==317235== 
==317235== 5 bytes in 1 blocks are still reachable in loss record 1 of 1
==317235==    at 0x483980B: malloc (vg_replace_malloc.c:309)
==317235==    by 0x40113E: main (1.cpp:7)
==317235== 
==317235== LEAK SUMMARY:
==317235==    definitely lost: 0 bytes in 0 blocks
==317235==    indirectly lost: 0 bytes in 0 blocks
==317235==      possibly lost: 0 bytes in 0 blocks
==317235==    still reachable: 5 bytes in 1 blocks
==317235==         suppressed: 0 bytes in 0 blocks
==317235== 
==317235== For lists of detected and suppressed errors, rerun with: -s
==317235== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

即使您 运行 Valgrind 没有任何选项,您也可以在 HEAP SUMMARY 部分看到问题:

==317235==     in use at exit: 5 bytes in 1 blocks

但没有更多细节。

内存泄漏意味着指向已分配内存的指针值丢失。一旦该值丢失,将无法再释放内存。

静态指针的生命周期是整个进程的执行。因此指针值永远不会丢失,因为它总是被存储,并且在程序的任何一点都不会出现无法释放指针的情况。

Valgrind documentation 将内存分类为:

"Still reachable". This covers cases 1 and 2 (for the BBB blocks) above. A start-pointer or chain of start-pointers to the block is found. Since the block is still pointed at, the programmer could, at least in principle, have freed it before program exit. "Still reachable" blocks are very common and arguably not a problem. So, by default, Memcheck won't report such blocks individually.


Is there some kind of "automatic free"

不是调用 free 的意思,但一旦程序停止,它就不再存在,它的分配也无关紧要。