Linux:检查程序中的内存泄漏

时间:2020-01-09 10:44:04  来源:igfitidea点击:

如何检查Linux操作系统下的C程序是否存在内存泄漏?
如何调试和分析Linux可执行文件?
您需要使用一个名为Valgrind的工具。
它是用于Linux和Mac OS X操作系统的内存调试,内存泄漏检测和性能分析工具。

Valgrind是用于调试和分析Linux可执行文件的灵活程序。
从官方网站:

Valgrind发行版目前包括六个生产质量工具:一个内存错误检测器,两个线程错误检测器,一个缓存和分支预测探查器,一个生成调用图的缓存探查器和一个堆探查器。
它还包括两个实验工具:堆/堆栈/全局数组溢出检测器和SimPoint基本块矢量生成器。
它可以在以下平台上运行:X86/Linux,AMD64/Linux,PPC32/Linux,PPC64/Linux和X86/Darwin(Mac OS X)。

如何安装Valgrind?

在CentOS/Redhat/RHEL Linux下执行以下命令:

# yum install valgrind

在Debian/Ubuntu Linux下执行以下命令:

# apt-get install valgrind

我如何使用Valgrind?

如果正常运行程序是这样的:

./a.out arg1 arg2

或者

/path/to/myapp arg1 arg2

使用此命令行打开详细的内存泄漏检测器:

valgrind --leak-check=yes ./a.out arg1 arg2
valgrind --leak-check=yes /path/to/myapp arg1 arg2

您还可以设置日志文件:

valgrind --log-file=output.file --leak-check=yes --tool=memcheck ./a.out arg1 arg2

大多数错误消息如下所示:

cat output.file

输出示例:

==43284== Memcheck, a memory error detector
==43284== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==43284== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==43284== Command: ./a.out
==43284== Parent PID: 39695
==43284== 
==43284== Invalid write of size 4
==43284==    at 0x4004B6: f (in /tmp/a.out)
==43284==    by 0x4004C6: main (in /tmp/a.out)
==43284==  Address 0x4c1c068 is 0 bytes after a block of size 40 alloc'd
==43284==    at 0x4A05E1C: malloc (vg_replace_malloc.c:195)
==43284==    by 0x4004A9: f (in /tmp/a.out)
==43284==    by 0x4004C6: main (in /tmp/a.out)
==43284== 
==43284== 
==43284== HEAP SUMMARY:
==43284==     in use at exit: 40 bytes in 1 blocks
==43284==   total heap usage: 1 allocs, 0 frees, 40 bytes allocated
==43284== 
==43284== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==43284==    at 0x4A05E1C: malloc (vg_replace_malloc.c:195)
==43284==    by 0x4004A9: f (in /tmp/a.out)
==43284==    by 0x4004C6: main (in /tmp/a.out)
==43284== 
==43284== LEAK SUMMARY:
==43284==    definitely lost: 40 bytes in 1 blocks
==43284==    indirectly lost: 0 bytes in 0 blocks
==43284==      possibly lost: 0 bytes in 0 blocks
==43284==    still reachable: 0 bytes in 0 blocks
==43284==         suppressed: 0 bytes in 0 blocks
==43284== 
==43284== For counts of detected and suppressed errors, rerun with: -v
==43284== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 4 from 4)

示例C程序

创建test.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 test.c
valgrind --log-file=output.file --leak-check=yes --tool=memcheck ./a.out
vi output.file