使用Valgrind查找内存泄露和程序崩溃

发布时间:2023-07-24 20:01:39 作者:yexindonglai@163.com 阅读(1056)

一、valgrind简介

Valgrind是一个GPL的软件,用于Linux(For x86, amd64 and ppc32)程序的内存调试和代码剖析。你可以在它的环境中运行你的程序来监视内存的使用情况,比如C 语言中的malloc和free或者 C++中的new和 delete。使用Valgrind的工具包,你可以自动的检测许多内存管理和线程的bug,避免花费太多的时间在bug寻找上,使得你的程序更加稳固。

二、安装valgrind

自行下载源码安装
  1. #1. 下载源码
  2. https://sourceware.org/pub/valgrind/valgrind-3.15.0.tar.bz2
  3. #2.解压tar文件
  4. tar -xjf valgrind-3.16.1.tar.bz2
  5. #3. 进入解压后的文件夹
  6. cd valgrind-3.16.1
  7. # 4. 配置编译参数
  8. ./configure
  9. #5. 编译
  10. make
  11. #6. 安装
  12. sudo make install
  13. # 7. 检查安装情况
  14. valgrind --version
在线安装
  1. # ubuntu系统
  2. sudo apt install valgrind -y
  3. # centos系统
  4. yum install valgrind -y

三、valgrind 使用

valgrind 格式

  1. valgrind [options] prog [args]

常用valgrind选项

在使用valgrind的过程中,可以使用很多选项来配置valgrind的行为。以下是一些常用的选项:

  1. --leak-check=full:检查内存泄漏
  2. --tool=helgrind:检查并发问题
  3. --tool=callgrind:检查程序的性能问题
  4. --trace-children=yes:跟踪子进程的情况
  5. --tool=<toolname>:指定要使用的 Valgrind 工具,例如 memcheck、helgrind、cachegrind 等。
  6. --leak-check=<yes|no|summary|full>:设置内存泄漏检测的级别,可以是 yes(默认,检测所有内存泄漏)、no(禁用内存泄漏检测)、summary(仅显示内存泄漏摘要)、full(显示详细的内存泄漏信息)。
  7. --show-reachable=<yes|no>:是否显示仍然可访问的内存块的信息。
  8. --track-origins=<yes|no>:是否跟踪未初始化值的来源。
  9. --trace-children=<yes|no>:是否跟踪子进程。
  10. --log-file=<filename>:将 Valgrind 输出重定向到指定的文件。
  11. --suppressions=<filename>:指定一个包含错误报告抑制规则的文件。
  12. --num-callers=<number>:设置堆栈跟踪中要显示的调用者数量。

valgrind主要功能

  1. memcheck:检查程序中的内存问题,如泄漏、越界、非法指针等。
  2. callgrind:检测程序代码的运行时间和调用过程,以及分析程序性能。
  3. cachegrind:分析CPU的cache命中率、丢失率,用于进行代码优化。
  4. helgrind:用于检查多线程程序的竞态条件。
  5. massif:堆栈分析器,指示程序中使用了多少堆内存等信息。
  6. lackey:
  7. nulgrind:
1、Memcheck

最常用的工具,用来检测程序中出现的内存问题,所有对内存的读写都会被检测到,一切对malloc、free、new、delete的调用都会被捕获。所以,Memcheck 工具主要检查下面的程序错误:

  1. 对未初始化内存的使用;
  2. 读/写释放后的内存块;
  3. 读/写超出malloc分配的内存块;
  4. 读/写不适当的栈中内存块;
  5. 内存泄漏,指向一块内存的指针永远丢失;
  6. 不正确的malloc/free或new/delete匹配;
  7. memcpy()相关函数中的dst和src指针重叠。

输出的错误信息翻译如下:

  • Invalid write of size 4 // 内存越界,或者对未分配内存的内存进行赋值操作;
  • Invalid free() / delete / delete[] // 重复释放
  • Use of uninitialised value of size 4 // 非法指针,使用了未分配内存的指针
  • Process terminating with default action of signal 11 (SIGSEGV) //由于非法指针赋值导致的程序崩溃
    2、Callgrind

和gprof类似的分析工具,但它对程序的运行观察更是入微,能给我们提供更多的信息。和gprof不同,它不需要在编译源代码时附加特殊选项,但加上调试选项是推荐的。Callgrind收集程序运行时的一些数据,建立函数调用关系图,还可以有选择地进行cache模拟。在运行结束时,它会把分析数据写入一个文件。callgrind_annotate可以把这个文件的内容转化成可读的形式。

使用示例,具体使用方法,请查阅相关资料

  1. valgrind --tool=callgrind ./tmp
3、Cachegrind

Cache分析器,它模拟CPU中的一级缓存I1,Dl和二级缓存,能够精确地指出程序中cache的丢失和命中。如果需要,它还能够为我们提供cache丢失次数,内存引用次数,以及每行代码,每个函数,每个模块,整个程序产生的指令数。这对优化程序有很大的帮助。

使用方法

  1. valgrind --tool=cachegrind ./程序名
4、Helgrind

它主要用来检查多线程程序中出现的竞争问题。Helgrind寻找内存中被多个线程访问,而又没有一贯加锁的区域,这些区域往往是线程之间失去同步的地方,而且会导致难以发掘的错误。Helgrind实现了名为“Eraser”的竞争检测算法,并做了进一步改进,减少了报告错误的次数。不过,Helgrind仍然处于实验阶段。

举个栗子

先编译程序:

  1. gcc -o test thread.c -lpthread

然后执行以下命令输出结果

  1. valgrind --tool=helgrind ./test
5、Massif

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

Massif对内存的分配和释放做profile。程序开发者通过它可以深入了解程序的内存使用行为,从而对内存使用进行优化。这个功能对C++尤其有用,因为C++有很多隐藏的内存分配和释放。

此外,lackey和nulgrind也会提供。Lackey是小型工具,很少用到;Nulgrind只是为开发者展示如何创建一个工具。我们就不做介绍了。

四、举个栗子

1、准备一个会崩溃的c++代码

main.cpp

  1. #include "iostream"
  2. #include "stdio.h"
  3. int main() {
  4. std::cout << "Hello, World! yeindong" << std::endl;
  5. int * p;
  6. *p =1;
  7. return 0;
  8. }
2、编译

必须加上-g选项,否则不会打印崩溃位置;

  1. g++ -g main.cpp -o main
3、运行valgrind
  1. # 以下2行都可以,当不指定tool参数时默认就是是 --tool=memcheck
  2. valgrind --tools=memcheck ./main
  3. valgrind ./main
4、结果分析

可以看到打印出了Use of uninitialised value of size 8Invalid write of size 4,非法访问指针和内存越界的错误,并且也指出了代码出错的位置main.cpp:7在main.cpp的第7行

  1. [root@master valgrind]# valgrind --tools=memcheck ./main
  2. valgrind: Unknown option: --tools=memcheck
  3. valgrind: Use --help for more information or consult the user manual.
  4. [root@master valgrind]# valgrind --tool=memcheck ./main
  5. ==9195== Memcheck, a memory error detector
  6. ==9195== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
  7. ==9195== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
  8. ==9195== Command: ./main
  9. ==9195==
  10. Hello, World! yeindong
  11. ==9195== Use of uninitialised value of size 8
  12. ==9195== at 0x400805: main (main.cpp:7)
  13. ==9195==
  14. ==9195== Invalid write of size 4
  15. ==9195== at 0x400805: main (main.cpp:7)
  16. ==9195== Address 0x0 is not stack'd, malloc'd or (recently) free'd
  17. ==9195==
  18. ==9195==
  19. ==9195== Process terminating with default action of signal 11 (SIGSEGV)
  20. ==9195== Access not within mapped region at address 0x0
  21. ==9195== at 0x400805: main (main.cpp:7)
  22. ==9195== If you believe this happened as a result of a stack
  23. ==9195== overflow in your program's main thread (unlikely but
  24. ==9195== possible), you can try to increase the size of the
  25. ==9195== main thread stack using the --main-stacksize= flag.
  26. ==9195== The main thread stack size used in this run was 8388608.
  27. ==9195==
  28. ==9195== HEAP SUMMARY:
  29. ==9195== in use at exit: 0 bytes in 0 blocks
  30. ==9195== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
  31. ==9195==
  32. ==9195== All heap blocks were freed -- no leaks are possible
  33. ==9195==
  34. ==9195== Use --track-origins=yes to see where uninitialised values come from
  35. ==9195== For lists of detected and suppressed errors, rerun with: -s
  36. ==9195== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
  37. Segmentation fault

举个例子-查找内存泄漏

准备代码 b.c

  1. #include "stdlib.h"
  2. #include "memory.h"
  3. int main() {
  4. void * a1 = malloc(2);
  5. void * a2 = malloc(20);
  6. void * a3 = malloc(22);
  7. free(a2);
  8. free(a3);
  9. }
编译
  1. gcc -o b b.c -g
使用valgrind进行检测
  1. valgrind --show-reachable=yes --leak-check=full ./b

结果如下,会告诉你第四行代码出现了内存泄漏

  1. ==3823== Memcheck, a memory error detector
  2. ==3823== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
  3. ==3823== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
  4. ==3823== Command: ./b
  5. ==3823==
  6. ==3823==
  7. ==3823== HEAP SUMMARY:
  8. ==3823== in use at exit: 2 bytes in 1 blocks
  9. ==3823== total heap usage: 3 allocs, 2 frees, 44 bytes allocated
  10. ==3823==
  11. ==3823== 2 bytes in 1 blocks are definitely lost in loss record 1 of 1
  12. ==3823== at 0x4848899: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
  13. ==3823== by 0x10917E: main (b.c:4)
  14. ==3823==
  15. ==3823== LEAK SUMMARY:
  16. ==3823== definitely lost: 2 bytes in 1 blocks
  17. ==3823== indirectly lost: 0 bytes in 0 blocks
  18. ==3823== possibly lost: 0 bytes in 0 blocks
  19. ==3823== still reachable: 0 bytes in 0 blocks
  20. ==3823== suppressed: 0 bytes in 0 blocks
  21. ==3823==
  22. ==3823== For lists of detected and suppressed errors, rerun with: -s
  23. ==3823== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

关键字c++