Valgrind安装与使用

  1. 下载:https://www.valgrind.org/docs/manual/manual-core.html#manual-core.started

  2. 解压

    tar -xjvf valgrind-3.16.0.tar.bz2
    
  3. 安装

    cd valgrind-3.16.0/
    
    ./autogen.sh
    ./configure
    make
    sudo make install
    

    可能需要先安装:

    sudo apt-get install autotools-dev
    sudo apt-get install automake
    
  4. 使用

    程序:

    a.c

    #include <stdlib.h>
    
    void f(void)
    {
       int* x = malloc(10 * sizeof(int));
       x[10] = 0;        // problem 1: heap block overrun
    }                    // problem 2: memory leak -- x not freed
    
    int main(void)
    {
       f();
       return 0;
    }
    

    运行:

    gcc -g -o a a.c   
    valgrind --leak-check=yes ./a
    

    输出:

    ==13545== Memcheck, a memory error detector
    ==13545== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
    ==13545== Using Valgrind-3.16.0 and LibVEX; rerun with -h for copyright info
    ==13545== Command: ./a
    ==13545==
    ==13545== error calling PR_SET_PTRACER, vgdb might block
    ==13545== Invalid write of size 4
    ==13545==    at 0x108668: f (a.c:6) # 第6行非法写入,一共是10个元素的int数组,却对x[10]写入
    ==13545==    by 0x108679: main (a.c:11)
    ==13545==  Address 0x522e068 is 0 bytes after a block of size 40 alloc'd
    ==13545==    at 0x4C2FECB: malloc (vg_replace_malloc.c:307)
    ==13545==    by 0x10865B: f (a.c:5)
    ==13545==    by 0x108679: main (a.c:11)
    ==13545==
    ==13545==
    ==13545== HEAP SUMMARY: # 检查出问题
    ==13545==     in use at exit: 40 bytes in 1 blocks
    ==13545==   total heap usage: 1 allocs, 0 frees, 40 bytes allocated
    ==13545==
    ==13545== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1 # 肯定丢失
    ==13545==    at 0x4C2FECB: malloc (vg_replace_malloc.c:307)
    ==13545==    by 0x10865B: f (a.c:5)
    ==13545==    by 0x108679: main (a.c:11)
    ==13545==
    ==13545== LEAK SUMMARY: # 内存泄漏
    ==13545==    definitely lost: 40 bytes in 1 blocks # 肯定丢失的部分,需要处理
    ==13545==    indirectly lost: 0 bytes in 0 blocks
    ==13545==      possibly lost: 0 bytes in 0 blocks
    ==13545==    still reachable: 0 bytes in 0 blocks
    ==13545==         suppressed: 0 bytes in 0 blocks
    ==13545==
    ==13545== For lists of detected and suppressed errors, rerun with: -s
    ==13545== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
    

参考https://www.jianshu.com/p/7ce24f278b0e

posted @ 2020-06-19 00:05  JayYin  阅读(391)  评论(0编辑  收藏  举报