为什么Valgrind在不释放分配的内存后不报告任何问题?

问题描述 投票:3回答:2

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

#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");
}

是否存在我不知道的某种“自动免费”功能,或者我是否缺少其他功能?

谢谢。

c++ malloc valgrind free
2个回答
5
投票

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

$ 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

但没有更多细节。


1
投票

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

静态指针的生存期是整个过程的执行。这样,指针值就永远不会丢失,因为它始终被存储,并且在程序的任何位置都不会出现无法释放指针的情况。

是否有某种“自动免费”

不是在调用free的意义上,而是一旦程序停止,它就不再存在,并且它的分配也就无关紧要。

© www.soinside.com 2019 - 2024. All rights reserved.