关于内存泄漏:valgrind memcheck报告错误肯定?

valgrind memcheck reports false positive?

这是我的代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char buf1[100];
char buf2[100];

int main()
{
    char **p = (char**)(buf1+sizeof(long));
    char **q = (char**)(buf2+1);
    *p = (char*)malloc(100);
    *q = (char*)malloc(100);

    strcpy(*p,"xxxx");
    strcpy(*q,"zzzz");

    printf("p:%s   q:%s\
", *p, *q);
    return 0;
}

我使用gcc编译了代码,并像这样运行valgrind-3.6.1

1
valgrind --leak-check=full --log-file=test.log  --show-reachable=yes  ~/a.out

valgrind给了我下面的日志

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
==20768== Memcheck, a memory error detector
==20768== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==20768== Using Valgrind-3.6.1 and LibVEX; rerun with -h for copyright info
==20768== Command: /home/zxin11/a.out
==20768== Parent PID: 12686
==20768==
==20768==
==20768== HEAP SUMMARY:
==20768==     in use at exit: 200 bytes in 2 blocks
==20768==   total heap usage: 2 allocs, 0 frees, 200 bytes allocated
==20768==
==20768== 100 bytes in 1 blocks are still reachable in loss record 1 of 2
==20768==    at 0x4C2488B: malloc (vg_replace_malloc.c:236)
==20768==    by 0x4005FD: main (test2.c:12)
==20768==
==20768== 100 bytes in 1 blocks are definitely lost in loss record 2 of 2
==20768==    at 0x4C2488B: malloc (vg_replace_malloc.c:236)
==20768==    by 0x400611: main (test2.c:13)
==20768==
==20768== LEAK SUMMARY:
==20768==    definitely lost: 100 bytes in 1 blocks
==20768==    indirectly lost: 0 bytes in 0 blocks
==20768==      possibly lost: 0 bytes in 0 blocks
==20768==    still reachable: 100 bytes in 1 blocks
==20768==         suppressed: 0 bytes in 0 blocks
==20768==
==20768== For counts of detected and suppressed errors, rerun with: -v
==20768== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 3 from 3)

为什么第一个malloc仍然可以访问而第二个malloc肯定丢失了?
也许是关于对齐的,您不能将已分配内存的地址放入未对齐的变量中,如果是这样,我该如何抑制这种肯定的报告?
非常想你。


从memcheck手册(重点为我):

If --leak-check is set appropriately, for each remaining block, Memcheck determines if the block is reachable from pointers within the root-set. The root-set consists of (a) general purpose registers of all threads, and (b) initialised, aligned, pointer-sized data words in accessible client memory, including stacks.

因此,您对对齐的猜想是正确的。不幸的是,最好地抑制这种警告的最佳方法可能只是在退出程序之前将任何这样的已知值复制到对齐的位置(大概此代码是您的实际应用程序的模型,对您而言某种意义上的意义)。存储未对齐的指针)。

您也可以尝试使用--gen-suppressions=yes写入或生成禁止文件。但是,如果您的应用程序是不确定的,或者您使用不同的输入数据运行它,则此方法将非常烦人。