• Linux/Unix使用valgrind内存泄漏检测


    cc++程序设计。内存管理是一个比较头疼的问题。相信它会导致内存泄漏。除了外部养成良好的编程习惯(使用智能指针),使用该工具还可以帮助检测内存泄漏,valgrind这是UnixLinux在一个很好的工具。

    (mac有暂时的bug)


    Valgrind 安装
    1. 到www.valgrind.org下载最新版valgrind-3.2.3.tar.bz2
    2. 解压安装包:tar –jxvf valgrind-3.2.3.tar.bz2
    3. 解压后生成文件夹valgrind-3.2.3
    4. cd valgrind-3.2.3
    5. 执行./autogen.sh设置环境(须要标准的autoconf工具)(可选)
    6. ./configure;配置Valgrind。生成MakeFile文件。详细參数信息详见INSTALL文件。一般仅仅须要设置—prefix=/where/you/want/it/installed
    7. Make;编译Valgrind
    8. make install;安装Valgrind

    ubuntu 直接用命令 sudo apt-get install valgrind安装
    Valgrind包括的工具
    Valgrind支持非常多工具:memcheck,addrcheck,cachegrind,Massif。helgrind和Callgrind等。在执行Valgrind时,你必须指明想用的工具,假设省略工具名,默认执行memcheck。

    1、memcheck

    memcheck探測程序中内存管理存在的问题。它检查全部对内存的读/写操作,并截取全部的malloc/new/free/delete调用。因此memcheck工具可以探測到下面问题:
    1)使用未初始化的内存
    2)读/写已经被释放的内存
    3)读/写内存越界
    4)读/写不恰当的内存栈空间
    5)内存泄漏
    6)使用malloc/new/new[]和free/delete/delete[]不匹配。
    7)src和dst的重叠

    2、cachegrind

    cachegrind是一个cache剖析器。

    它模拟运行CPU中的L1, D1和L2 cache。因此它能非常精确的指出代码中的cache未命中。假设你须要。它能够打印出cache未命中的次数,内存引用和发生cache未命中的每一行代码,每个函数,每个模块和整个程序的摘要。假设你要求更仔细的信息,它能够打印出每一行机器码的未命中次数。在x86和amd64上, cachegrind通过CPUID自己主动探測机器的cache配置,所以在多数情况下它不再须要很多其它的配置信息了。

    3、helgrind

    helgrind查找多线程程序中的竞争数据。helgrind查找内存地址。那些被多于一条线程訪问的内存地址。可是没有使用一致的锁就会被查出。这表示这些地址在多线程间訪问的时候没有进行同步,非常可能会引起非常难查找的时序问题。


    它主要用来检查多线程程序中出现的竞争问题。

    Helgrind 寻找内存中被多个线程訪问,而又没有一贯加锁的区域,这些区域往往是线程之间失去同步的地方。并且会导致难以发掘的错误。Helgrind实现了名为”Eraser” 的竞争检測算法,并做了进一步改进,降低了报告错误的次数。

    4、Callgrind

    Callgrind收集程序执行时的一些数据,函数调用关系等信息,还能够有选择地进行cache 模拟。

    在执行结束时,它会把分析数据写入一个文件。callgrind_annotate能够把这个文件的内容转化成可读的形式。
    一般使用方法:
    $valgrind —tool=callgrind ./sec_infod
    会在当前文件夹下生成callgrind.out.[pid], 假设我们想结束程序, 能够
    $killall callgrind
    然后我们能够用
    $callgrind_annotate —auto=yes callgrind.out.[pid] > log
    $vi log

    5、Massif

    堆栈分析器,它能測量程序在堆栈中使用了多少内存,告诉我们堆块。堆管理块和栈的大小。Massif能帮助我们降低内存的使用。在带有虚拟内存的现代系统中,它还可以加速我们程序的执行。降低程序停留在交换区中的几率。

    6、lackey

    lackey是一个演示样例程序。以其为模版能够创建你自己的工具。

    在程序结束后。它打印出一些主要的关于程序运行统计数据。

    Valgrind的參数

    使用方法: valgrind [options] prog-and-args [options]: 经常使用选项。适用于全部####Valgrind工具
    —tool=
    最经常使用的选项。执行 valgrind中名为toolname的工具。

    默认memcheck。
    -h —help
    显示全部选项的帮助,包含内核和选定的工具两者。


    —version
    显示valgrind内核的版本号,每一个工具都有各自的版本号。
    -q —quiet
    安静地执行,仅仅打印错误信息。


    —verbose
    更具体的信息。
    —trace-children=
    跟踪子线程? [default: no]
    —track-fds=
    跟踪打开的文件描写叙述?[default: no]
    —time-stamp=
    添加时间戳到LOG信息? [default: no]
    —log-fd=
    输出LOG到描写叙述符文件 [2=stderr]
    —log-file=
    将输出的信息写入到filename.PID的文件中,PID是执行程序的进行ID
    —log-file-exactly=
    输出LOG信息到 file
    LOG信息输出
    —xml=yes
    将信息以xml格式输出,仅仅有memcheck可用
    —num-callers=
    show callers in stack traces [12]
    —error-exitcode=
    假设发现错误则返回错误代码 [0=disable]
    —db-attach=
    当出现错误,valgrind会自己主动启动调试器gdb。[default: no]
    —db-command=
    启动调试器的命令行选项[gdb -nw %f %p]
    适用于Memcheck工具的相关选项:
    —leak-check=
    要求对leak给出具体信息?

    Leak是指,存在一块没有被引用的内存空间,或没有被释放的内存空间。如summary,仅仅反馈一些总结信息,告诉你有多少个malloc。多少个free 等;假设是full将输出全部的leaks。也就是定位到某一个malloc/free。

    [default: summary]
    —show-reachable=
    假设为no。仅仅输出没有引用的内存leaks。或指向malloc返回的内存块中部某处的leaks [default: no]
    更具体的參数指令见附录A。


    Valgrind的使用
    首先。在编译程序的时候打开调试模式(gcc编译器的-g选项)。

    假设没有调试信息。即使最好的valgrind工具也将中可以推測特定的代码是属于哪一个函数。打开调试选项进行编译后再用valgrind检查,valgrind将会给你的个具体的报告。比方哪一行代码出现了内存泄漏。
    当检查的是C++程序的时候。还应该考虑还有一个选项 -fno-inline。它使得函数调用链非常清晰,这样能够降低你在浏览大型C++程序时的混乱。比方在使用这个选项的时候,用memcheck检查openoffice就非常easy。

    当然,你可能不会做这项工作,可是使用这一选项使得valgrind生成更精确的错误报告和降低混乱。
    一些编译优化选项(比方-O2或者更高的优化选项),可能会使得memcheck提交错误的未初始化报告。因此,为了使得valgrind的报告更精确。在编译的时候最好不要使用优化选项。
    假设程序是通过脚本启动的。能够改动脚本里启动程序的代码。或者使用—trace-children=yes选项来执行脚本。
    以下是用memcheck检查sample.c的样例
    这里用到的演示样例程序文件名称为:sample.c(例如以下所看到的),选用的编译器为gcc。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    /* sample.c */
    #include <stdlib.h>
    void fun()
    {
    int *p = (int*)malloc(10*sizeof(int));
    p[10] = 0;
    }
    int main(void)
    {
    fun();
    return 0;
    }

    生成可运行程序
    gcc –g sample.c –o sample
    执行Valgrind
    valgrind --tool=memcheck ./sample
    下面是执行上述命令后的输出
    ==23913== Memcheck, a memory error detector
    ==23913== Copyright (C) 2002-2013, and GNU GPL’d, by Julian Seward et al.
    ==23913== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
    ==23913== Command: ./sample
    ==23913==
    ==23913== Invalid write of size 4
    ==23913== at 0x8048438: fun (sample.c:6)
    ==23913== by 0x804844A: main (sample.c:11)
    ==23913== Address 0x4204050 is 0 bytes after a block of size 40 alloc’d
    ==23913== at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
    ==23913== by 0x804842E: fun (sample.c:5)
    ==23913== by 0x804844A: main (sample.c:11)
    ==23913==
    ==23913==
    ==23913== HEAP SUMMARY:
    ==23913== in use at exit: 40 bytes in 1 blocks
    ==23913== total heap usage: 1 allocs, 0 frees, 40 bytes allocated
    ==23913==
    ==23913== LEAK SUMMARY:
    ==23913== definitely lost: 40 bytes in 1 blocks
    ==23913== indirectly lost: 0 bytes in 0 blocks
    ==23913== possibly lost: 0 bytes in 0 blocks
    ==23913== still reachable: 0 bytes in 0 blocks
    ==23913== suppressed: 0 bytes in 0 blocks
    ==23913== Rerun with —leak-check=full to see details of leaked memory
    ==23913==
    ==23913== For counts of detected and suppressed errors, rerun with: -v
    ==23913== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
    左边显示类似行号的数字(23913)表示的是 Process ID。
    最上面的红色方框表示的是 valgrind 的版本号信息。
    中间的红色方框表示 valgrind 通过执行被測试程序。发现的内存问题。通过阅读这些信息,能够发现:
    l 这是一个对内存的非法写操作。非法写操作的内存是4 bytes。


    l 错误发生时的函数堆栈,以及详细的源码行号。
    l 非法写操作的详细地址空间。
    最以下的红色方框是对发现的内存问题和内存泄漏问题的总结。

    内存泄漏的大小(40 bytes)也可以被检測出来。
    Valgrind的演示样例
    例1.使用未初始化的内存
    代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    #include <stdio.h>
    int main()
    {
    int x;
    if(x == 0)
    {
    printf("X is zero");
    }
    return 0;
    }

    Valgrind提演示样例如以下
    ==14222== Conditional jump or move depends on uninitialised value(s)
    ==14222== at 0x400484: main (sample2.c:6)
    X is zero==14222==
    ==14222== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 5 from 1)
    ==14222== malloc/free: in use at exit: 0 bytes in 0 blocks.
    ==14222== malloc/free: 0 allocs, 0 frees, 0 bytes allocated.
    ==14222== For counts of detected errors, rerun with: -v
    ==14222== All heap blocks were freed — no leaks are possible.
    例2.内存读写越界
    代码例如以下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    #include <stdlib.h>
    #include <stdio.h>
    int main(int argc,char *argv[])
    {
    int len=5;
    int i;
    int *pt=(int*)malloc(len*sizeof(int));
    int *p=pt;
    for(i=0;i<len;i++)
    {p++;}
    *p=5;
    printf(“%d”,*p);
    return;
    }

    Valgrind提演示样例如以下
    ==23045== Invalid write of size 4
    ==23045== at 0x40050A: main (sample2.c:11)
    ==23045== Address 0x4C2E044 is 0 bytes after a block of size 20 alloc’d
    ==23045== at 0x4A05809: malloc (vg_replace_malloc.c:149)
    ==23045== by 0x4004DF: main (sample2.c:7)
    ==23045==
    ==23045== Invalid read of size 4
    ==23045== at 0x400514: main (sample2.c:12)
    ==23045== Address 0x4C2E044 is 0 bytes after a block of size 20 alloc’d
    ==23045== at 0x4A05809: malloc (vg_replace_malloc.c:149)
    ==23045== by 0x4004DF: main (sample2.c:7)
    5==23045==
    ==23045== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 5 from 1)
    ==23045== malloc/free: in use at exit: 20 bytes in 1 blocks.
    ==23045== malloc/free: 1 allocs, 0 frees, 20 bytes allocated.
    ==23045== For counts of detected errors, rerun with: -v
    ==23045== searching for pointers to 1 not-freed blocks.
    ==23045== checked 66,584 bytes.
    ==23045==
    ==23045== LEAK SUMMARY:
    ==23045== definitely lost: 20 bytes in 1 blocks.
    ==23045== possibly lost: 0 bytes in 0 blocks.
    ==23045== still reachable: 0 bytes in 0 blocks.
    ==23045== suppressed: 0 bytes in 0 blocks.
    ==23045== Use —leak-check=full to see details of leaked memory.
    例3.src和dst内存覆盖
    代码例如以下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    int main(int argc,char *argv[])
    {
    char x[50];
    int i;
    for(i=0;i<50;i++)
    {x[i]=i;}
    strncpy(x+20,x,20); //Good
    strncpy(x+20,x,21); //Overlap
    x[39]=’0’;
    strcpy(x,x+20); //Good
    x[39]=40;
    x[40]=’0’;
    strcpy(x,x+20); //Overlap
    return 0;
    }

    Valgrind提演示样例如以下
    ==24139== Source and destination overlap in strncpy(0x7FEFFFC09, 0x7FEFFFBF5, 21)
    ==24139== at 0x4A0724F: strncpy (mc_replace_strmem.c:116)
    ==24139== by 0x400527: main (sample3.c:10)
    ==24139==
    ==24139== Source and destination overlap in strcpy(0x7FEFFFBE0, 0x7FEFFFBF4)
    ==24139== at 0x4A06E47: strcpy (mc_replace_strmem.c:106)
    ==24139== by 0x400555: main (sample3.c:15)
    ==24139==
    ==24139== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 5 from 1)
    ==24139== malloc/free: in use at exit: 0 bytes in 0 blocks.
    ==24139== malloc/free: 0 allocs, 0 frees, 0 bytes allocated.
    ==24139== For counts of detected errors, rerun with: -v
    ==24139== All heap blocks were freed — no leaks are possible.
    例4.动态内存管理错误
    常见的内存分配方式分三种:静态存储,栈上分配。堆上分配。全局变量属于静态存储。它们是在编译时就被分配了存储空间,函数内的局部变量属于栈上分配,而最灵活的内存使用方式当属堆上分配。也叫做内存动态分配了。经常使用的内存动态分配函数包含:malloc, alloc, realloc, new等。动态释放函数包含free, delete。
    一旦成功申请了动态内存,我们就须要自己对其进行内存管理。而这又是最easy犯错误的。常见的内存动态管理错误包含:
    l 申请和释放不一致
    因为 C++ 兼容 C,而 C 与 C++ 的内存申请和释放函数是不同的,因此在 C++ 程序中。就有两套动态内存管理函数。一条不变的规则就是採用 C 方式申请的内存就用 C 方式释放。用 C++ 方式申请的内存,用 C++ 方式释放。也就是用 malloc/alloc/realloc 方式申请的内存,用 free 释放;用 new 方式申请的内存用 delete 释放。在上述程序中,用 malloc 方式申请了内存却用 delete 来释放,尽管这在非常多情况下不会有问题。但这绝对是潜在的问题。
    l 申请和释放不匹配
    申请了多少内存,在使用完毕后就要释放多少。

    假设没有释放。或者少释放了就是内存泄露;多释放了也会产生问题。上述程序中。指针p和pt指向的是同一块内存,却被先后释放两次。


    l 释放后仍然读写
    本质上说,系统会在堆上维护一个动态内存链表。假设被释放,就意味着该块内存能够继续被分配给其它部分。假设内存被释放后再訪问,就可能覆盖其它部分的信息。这是一种严重的错误,上述程序第16行中就在释放后仍然写这块内存。
    以下的一段程序。就包含了内存动态管理中常见的错误.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    #include <stdlib.h>
    #include <stdio.h>
    int main(int argc,char *argv[])
    {
    char *p=(char*)malloc(10);
    char *pt=p;
    int i;
    for(i=0;i<10;i++)
    {p[i]=’z’;}
    delete p;
    p[1]=’a’;
    free(pt);
    return 0;
    }

    Valgrind提演示样例如以下
    ==25811== Mismatched free() / delete / delete []
    ==25811== at 0x4A05130: operator delete(void) (vg_replace_malloc.c:244)
    ==25811== by 0x400654: main (sample4.c:9)
    ==25811== Address 0x4C2F030 is 0 bytes inside a block of size 10 alloc’d
    ==25811== at 0x4A05809: malloc (vg_replace_malloc.c:149)
    ==25811== by 0x400620: main (sample4.c:4)
    ==25811==
    ==25811== Invalid write of size 1
    ==25811== at 0x40065D: main (sample4.c:10)
    ==25811== Address 0x4C2F031 is 1 bytes inside a block of size 10 free’d
    ==25811== at 0x4A05130: operator delete(void
    ) (vg_replace_malloc.c:244)
    ==25811== by 0x400654: main (sample4.c:9)
    ==25811==
    ==25811== Invalid free() / delete / delete[]
    ==25811== at 0x4A0541E: free (vg_replace_malloc.c:233)
    ==25811== by 0x400668: main (sample4.c:11)
    ==25811== Address 0x4C2F030 is 0 bytes inside a block of size 10 free’d
    ==25811== at 0x4A05130: operator delete(void*) (vg_replace_malloc.c:244)
    ==25811== by 0x400654: main (sample4.c:9)
    ==25811==
    ==25811== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 5 from 1)
    ==25811== malloc/free: in use at exit: 0 bytes in 0 blocks.
    ==25811== malloc/free: 1 allocs, 2 frees, 10 bytes allocated.
    ==25811== For counts of detected errors, rerun with: -v
    ==25811== All heap blocks were freed — no leaks are possible.
    例5.内存泄漏
    代码例如以下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    #include <stdlib.h>
    int main()
    {
    char *x = (char*)malloc(20);
    char *y = (char*)malloc(20);
    x=y;
    free(x);
    free(y);
    return 0;
    }

    Valgrind提演示样例如以下
    ==19013== Invalid free() / delete / delete[]
    ==19013== at 0x4A0541E: free (vg_replace_malloc.c:233)
    ==19013== by 0x4004F5: main (sample5.c:8)
    ==19013== Address 0x4C2E078 is 0 bytes inside a block of size 20 free’d
    ==19013== at 0x4A0541E: free (vg_replace_malloc.c:233)
    ==19013== by 0x4004EC: main (sample5.c:7)
    ==19013==
    ==19013== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 5 from 1)
    ==19013== malloc/free: in use at exit: 20 bytes in 1 blocks.
    ==19013== malloc/free: 2 allocs, 2 frees, 40 bytes allocated.
    ==19013== For counts of detected errors, rerun with: -v
    ==19013== searching for pointers to 1 not-freed blocks.
    ==19013== checked 66,584 bytes.
    ==19013==
    ==19013== LEAK SUMMARY:
    ==19013== definitely lost: 20 bytes in 1 blocks.
    ==19013== possibly lost: 0 bytes in 0 blocks.
    ==19013== still reachable: 0 bytes in 0 blocks.
    ==19013== suppressed: 0 bytes in 0 blocks.
    ==19013== Use —leak-check=full to see details of leaked memory.
    例6.非法写/读
    代码例如以下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    int main()
    {
    int i, *x;
    x = (int *)malloc(10*sizeof(int));
    for (i=0; i<11; i++)
    x[i] = i;
    free(x);
    }

    Valgrind提演示样例如以下
    ==21483== Invalid write of size 4
    ==21483== at 0x4004EA: main (sample6.c:6)
    ==21483== Address 0x4C2E058 is 0 bytes after a block of size 40 alloc’d
    ==21483== at 0x4A05809: malloc (vg_replace_malloc.c:149)
    ==21483== by 0x4004C9: main (sample6.c:4)
    ==21483==
    ==21483== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 5 from 1)
    ==21483== malloc/free: in use at exit: 0 bytes in 0 blocks.
    ==21483== malloc/free: 1 allocs, 1 frees, 40 bytes allocated.
    ==21483== For counts of detected errors, rerun with: -v
    ==21483== All heap blocks were freed — no leaks are possible.
    例7.无效指针
    代码例如以下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #include <stdlib.h>
    int main()
    {
    char *x = malloc(10);
    x[10] = 'a';
    free(x);
    return 0;
    }

    Valgrind提演示样例如以下
    ==15262== Invalid write of size 1
    ==15262== at 0x4004D6: main (sample7.c:5)
    ==15262== Address 0x4C2E03A is 0 bytes after a block of size 10 alloc’d
    ==15262== at 0x4A05809: malloc (vg_replace_malloc.c:149)
    ==15262== by 0x4004C9: main (sample7.c:4)
    ==15262==
    ==15262== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 5 from 1)
    ==15262== malloc/free: in use at exit: 0 bytes in 0 blocks.
    ==15262== malloc/free: 1 allocs, 1 frees, 10 bytes allocated.
    ==15262== For counts of detected errors, rerun with: -v
    ==15262== All heap blocks were freed — no leaks are possible.
    例8.反复释放
    代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #include <stdlib.h>
    int main()
    {
    char *x = malloc(10);
    free(x);
    free(x);
    return 0;
    }

    Valgrind提演示样例如以下
    ==15005== Invalid free() / delete / delete[]
    ==15005== at 0x4A0541E: free (vg_replace_malloc.c:233)
    ==15005== by 0x4004DF: main (sample8.c:6)
    ==15005== Address 0x4C2E030 is 0 bytes inside a block of size 10 free’d
    ==15005== at 0x4A0541E: free (vg_replace_malloc.c:233)
    ==15005== by 0x4004D6: main (sample8.c:5)
    ==15005==
    ==15005== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 5 from 1)
    ==15005== malloc/free: in use at exit: 0 bytes in 0 blocks.
    ==15005== malloc/free: 1 allocs, 2 frees, 10 bytes allocated.
    ==15005== For counts of detected errors, rerun with: -v
    ==15005== All heap blocks were freed — no leaks are possible.

    Valgrind的局限

    l Valgrind不正确静态数组(分配在栈上)进行边界检查。假设在程序中声明了一个数组:

    1
    2
    3
    4
    5
    int main()
    {
    char x[10];
    x[11] = 'a';
    }

    Valgrind则不会警告你,你能够把数组改为动态在堆上分配的数组,这样就可能进行边界检查了。这种方法好像有点得不偿失的感觉。


    l Valgrind占用了很多其它的内存—可达两倍于你程序的正常使用量。假设你用Valgrind来检測使用大量内存的程序就会遇到问题,它可能会用非常长的时间来执行測试。

    大多数情况下。这都不是问题。即使速度慢也仅是检測时速度慢,假设你用Valgrind来检測一个正常执行时速度就非常慢的程序,这下问题就大了。 Valgrind不可能检測出你在程序中犯下的全部错误—假设你不检查缓冲区溢出。Valgrind也不会告诉你代码写了它不应该写的内存。


    參考:

    Valgrind User Manual
    应用Valgrind发现Linux程序性记忆问题

    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    vue使用百度统计埋点
    修改JAVA字节码
    由前序遍历和中序遍历构建二叉树-Python
    二叉树的最大深度-Python
    二叉树的层序遍历-Python
    判断是否是对称二叉搜索树
    什么是主动学习方法
    验证二叉搜索树-Python
    DevExpress如何汉化XAF
    python install 失败?
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/4667219.html
Copyright © 2020-2023  润新知