为什么valgrind会将我的记忆报告为"肯定会失去"?

时间:2015-06-25 21:45:07

标签: c memory-leaks valgrind

考虑以下代码:

#include <stdlib.h>

int* alloc()
{
    return malloc(250 * sizeof(int));
}

int main()
{
    int i;
    int *vars[3];
    for(i = 0; i < 3; ++i) {
        vars[i] = alloc();
    }
}

Valgrind输出:

$ valgrind --leak-check=full ./lala
==16775== Memcheck, a memory error detector
==16775== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==16775== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==16775== Command: ./lala
==16775== 
==16775== 
==16775== HEAP SUMMARY:
==16775==     in use at exit: 3,000 bytes in 3 blocks
==16775==   total heap usage: 3 allocs, 0 frees, 3,000 bytes allocated
==16775== 
==16775== 3,000 bytes in 3 blocks are definitely lost in loss record 1 of 1
==16775==    at 0x4C2BBA0: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==16775==    by 0x4005B3: alloc (lala.c:5)
==16775==    by 0x4005DF: main (lala.c:13)
==16775== 
==16775== LEAK SUMMARY:
==16775==    definitely lost: 3,000 bytes in 3 blocks
==16775==    indirectly lost: 0 bytes in 0 blocks
==16775==      possibly lost: 0 bytes in 0 blocks
==16775==    still reachable: 0 bytes in 0 blocks
==16775==         suppressed: 0 bytes in 0 blocks
==16775== 
==16775== For counts of detected and suppressed errors, rerun with: -v
==16775== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

根据Valgrind's manual

  

如果--leak-check设置正确,对于每个剩余的块,   Memcheck确定块是否可以从指针内的指针访问   根设置。根集包括(a)通用寄存器   所有线程,以及(b)初始化,对齐,指针大小的数据字   可访问的客户端内存,包括堆栈。

据我了解,因为&#34;肯定失去了#34;内存仍然从main()函数堆栈中指向,它们应归类为&#34;仍然可以访问&#34;,对吧?

如果没有,我如何配置Valgrind尝试从main的堆栈到达内存块,以确定它们是否仍然可以到达&#34;?

修改

请不要告诉我free main末尾的指针,这不是我要问的问题。为了区分&#34;仍然可以到达&#34;并且&#34;绝对丢失&#34;在Valgrind术语上,请参阅此答案:https://stackoverflow.com/a/3857638/578749

1 个答案:

答案 0 :(得分:9)

main的堆栈被破坏时,即它返回时,你的内存肯定会丢失。因此,解决方案不是回归。

#include <stdlib.h>
int main()
{
    /* your code here */
    exit(0);
}

行为或主要返回0或exit(0)应该是等效的。

现在输出是:

==5035== Memcheck, a memory error detector
==5035== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==5035== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==5035== Command: ./a.out
==5035== 
==5035== 
==5035== HEAP SUMMARY:
==5035==     in use at exit: 3,000 bytes in 3 blocks
==5035==   total heap usage: 3 allocs, 0 frees, 3,000 bytes allocated
==5035== 
==5035== LEAK SUMMARY:
==5035==    definitely lost: 0 bytes in 0 blocks
==5035==    indirectly lost: 0 bytes in 0 blocks
==5035==      possibly lost: 0 bytes in 0 blocks
==5035==    still reachable: 3,000 bytes in 3 blocks
==5035==         suppressed: 0 bytes in 0 blocks
==5035== Reachable blocks (those to which a pointer was found) are not shown.
==5035== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==5035== 
==5035== For counts of detected and suppressed errors, rerun with: -v
==5035== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)