检查程序是否有内存泄漏:valgrind 的用法

以 test 程序为例,test.c 代码:

#include<stdio.h>
#include<stdlib.h>

void main()
{
       void*  p = malloc(100);
       if(NULL == p)
            printf("malloc failed.\n");
       printf("---------------- test end --------------\n");
       return;
}


编译生成test执行文件:

[root@localhost test]# gcc -o test test.c

用 valgrind 检查test是否有内存泄漏:

[root@localhost test]# valgrind --tool=memcheck --leak-check=full ./test
==9407== Memcheck, a memory error detector
==9407== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==9407== Using Valgrind-3.6.0 and LibVEX; rerun with -h for copyright info
==9407== Command: ./test
==9407==
---------------- test end --------------
==9407==
==9407== HEAP SUMMARY:
==9407==     in use at exit: 100 bytes in 1 blocks
==9407==   total heap usage: 1 allocs, 0 frees, 100 bytes allocated
==9407==
==9407== 100 bytes in 1 blocks are definitely lost in loss record 1 of 1
==9407==    at 0x4A05FDE: malloc (vg_replace_malloc.c:236)
==9407==    by 0x400515: main (in /data/test/test)
==9407==
==9407== LEAK SUMMARY:
==9407==    definitely lost: 100 bytes in 1 blocks
==9407==    indirectly lost: 0 bytes in 0 blocks
==9407==      possibly lost: 0 bytes in 0 blocks
==9407==    still reachable: 0 bytes in 0 blocks
==9407==         suppressed: 0 bytes in 0 blocks
==9407==
==9407== For counts of detected and suppressed errors, rerun with: -v
==9407== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 6 from 6)
[root@localhost test]#


检查到有100个字节的空间没释放:

==9407==    definitely lost: 100 bytes in 1 blocks


如果是全局指针所指的内存没有释放,“still reachable” 提示,但 “definitely lost” 不提示,如下:

test.c 文件

#include <stdio.h>
#include <stdlib.h>

void*  p;

int main()
{
        p = malloc(100);
        //free(p);
        return 0;
}

[root@localhost test]$ valgrind --tool=memcheck --leak-check=full ./test
==4696== Memcheck, a memory error detector
==4696== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==4696== Using Valgrind-3.6.0 and LibVEX; rerun with -h for copyright info
==4696== Command: ./test
==4696==
==4696==
==4696== HEAP SUMMARY:
==4696==     in use at exit: 100 bytes in 1 blocks
==4696==   total heap usage: 1 allocs, 0 frees, 100 bytes allocated
==4696==
==4696== LEAK SUMMARY:
==4696==    definitely lost: 0 bytes in 0 blocks
==4696==    indirectly lost: 0 bytes in 0 blocks
==4696==      possibly lost: 0 bytes in 0 blocks
==4696==    still reachable: 100 bytes in 1 blocks
==4696==         suppressed: 0 bytes in 0 blocks
==4696== Reachable blocks (those to which a pointer was found) are not shown.
==4696== To see them, rerun with: --leak-check=full --show-reachable=yes
==4696==
==4696== For counts of detected and suppressed errors, rerun with: -v
==4696== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 6)
[root@localhost test]$


你可能感兴趣的:(检查程序是否有内存泄漏:valgrind 的用法)