C/C++的内存泄漏检测工具Valgrind memcheck的使用经历


 

C/C++的内存泄漏检测工具Valgrind memcheck的使用经历

分类: C/C++编程 工具收藏   404人阅读  评论(0)  收藏  举报

目录(?)[+]

Linux下的Valgrind真是利器啊(不知道Valgrind的请自觉查看参考文献(1)(2)),帮我找出了不少C++中的内存管理错误,前一阵子还在纠结为什么VS 2013下运行良好的程序到了Linux下用g++编译运行却崩溃了,给出一堆汇编代码也看不懂。久久不得解过后,想想肯定是内存方面的错误,VS在这方面一般都不检查的,就算你的程序千疮百孔,各种内存泄露、内存管理错误,只要不影响运行,没有读到不该读的东西VS就不会告诉你(应该是VS内部没实现这个内存检测功能),因此用VS写出的程序可能不是完美或健壮的。

------------------------------------------------------------------------------------------------------------------------------

更新感谢博客园好心网友@shines77的热心推荐,即VS中有内存泄漏检测工具插件VLD(Visual Leak Detector),需要下载安装,安装方法请看官方介绍,使用非常简单,在第一个入口文件里加上#include <vld.h>就可以了,检测报告在输出窗口中。我安装使用了下,不知道是安装错误还是什么,无论程序有无内存泄露,输出都是“No memory leaks detected.”


下面是我通过 Valgrind第一次检测得到的结果和一点点修改后得到的结果(还没改完,所以还有不少内存泄露问题……):

第一次检测结果:惨不忍睹,因为程序规模有些大。


 

根据提示一点点修改过后,虽然还有个别错误和内存泄露问题,但还在修改中,至少已经能成功运行了……


 

真感谢Valgrind帮我成功找出了一堆内存问题,查找过程中也为自己犯的低级错误而感到羞愧,所以记录下来以便谨记。


1. 最多最低级的错误:不匹配地使用malloc/new/new[] 和 free/delete/delete[]

这样的错误主要源于我对C++的new/new[]、delete/delete[]机制不熟悉,凡是new/new[]分配内存的类型变量我一概用delete进行释放,或者有的变量用malloc进行分配,结果释放的时候却用delete,导致申请、释放很多地方不匹配,很多内存空间没能释放掉。为了维护方便,我后来一律使用new/new[]和delete/delete[],抛弃C中的malloc和free。

如果将用户new的类型分为基本数据类型和自定义数据类型两种,那么对于下面的操作相信大家都很熟悉,也没有任何问题。

(1)基本数据类型

一维指针:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // 申请空间  
  2. int *d = new int[5];  
  3.   
  4. // 释放空间  
  5. delete[] d;  

二维指针:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // 申请空间  
  2. int **d = new int*[5];  
  3. for (int i = 0; i < 5; i++)  
  4.     d[i] = new int[10];  
  5.   
  6. // 释放空间  
  7. for (int i = 0; i < 5; i++)  
  8.     delete[] d[i];  
  9. delete[] d;  

(2)自定义数据类型

比如下面这样一个类型:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. class DFA {  
  2.     bool is_mark;  
  3.     char *s;  
  4.   
  5. public:  
  6.      ~DFA() { printf("delete it.\n"); }  
  7. };  

一维指针:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. DFA *d = new DFA();  
  2. delete d;  

二维指针:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // 申请空间  
  2. DFA **d = new DFA*[5];  
  3. for (int i = 0; i < 5; i++)  
  4.     d[i] = new DFA();  
  5.   
  6. // 释放空间  
  7. for (int i = 0; i < 5; i++)  
  8.     delete d[i];  
  9. delete[]d;  

这没有任何问题,因为我们都是配套使用new/delete和new[]/delete[]的。这在Valgrind下检测也是完美通过的,但为什么要这配套使用呢?原理是什么?

虽然深究这些东西好像没什么实际意义,但对于想深入了解C++内部机制或像我一样老是释放出错导致大量内存泄露的小白程序员还是值得研究的,至少知道了为什么,以后就不会犯现在的低级错误。

参考文献(3)是这样描述的:

通常状况下,编译器在new的时候会返回用户申请的内存空间大小,但是实际上,编译器会分配更大的空间,目的就是在delete的时候能够准确的释放这段空间
这段空间在用户取得的指针之前以及用户空间末尾之后存放。

实际上:blockSize = sizeof(_CrtMemBlockHeader) + nSize + nNoMansLandSize; 其中,blockSize 是系统所分配的实际空间大小,
_CrtMemBlockHeader是new的头部信息,其中包含用户申请的空间大小等其他一些信息。 nNoMansLandSize是尾部的越界校验大小,
一般是4个字节“FEFEFEFE”,如果用户越界写入这段空间,则校验的时候会assert。nSize才是为我们分配的真正可用的内存空间。

用户new的时候分为两种情况
A. new的是基础数据类型或者是没有自定义析构函数的结构
B. new的是有自定义析构函数的结构体或类

这两者的区别是如果有用户自定义的析构函数,则delete的时候必须要调用析构函数,那么编译器delete时如何知道要调用多少个对象的析构函数呢,
答案就是new的时候,如果是情况B,则编译器会在new头部之后,用户获得的指针之前多分配4个字节的空间用来记录new的时候的数组大小,
这样delete的时候就可以取到个数并正确的调用。

这段描述可能有些晦涩难懂,参考文献(4)给了更加详细的解释,一点即通。这样的解释其实也隐含着一个推论:如果new的是基本数据类型或者是没有自定义析构函数的结构,那么这种情况下编译器不会在用户获得的指针之前多分配4个字节,因为这时候delete时不用调用析构函数,也就是不用知道数组个数的大小(因为只有调用析构函数时才需要知道要调用多少个析构函数,也就是数组的大小),而是直接传入数组的起始地址从而释放掉这块内存空间,此时delete与delete[]是等价的。

因此下面的释放操作也是正确的:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // 申请空间  
  2. int *d = new int[5];  
  3.   
  4. // 释放空间  
  5. delete d;  

将其放在Valgrind下进行检测,结果如下:

==2955== Memcheck, a memory error detector
==2955== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==2955== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==2955== Command: ./test_int
==2955== 
==2955== Mismatched free() / delete / delete []
==2955==    at 0x402ACFC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2955==    by 0x8048530: main (in /home/hadoop/test/test_int)
==2955==  Address 0x434a028 is 0 bytes inside a block of size 20 alloc'd
==2955==    at 0x402B774: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2955==    by 0x8048520: main (in /home/hadoop/test/test_int)
==2955== 
==2955== 
==2955== HEAP SUMMARY:
==2955==     in use at exit: 0 bytes in 0 blocks
==2955==   total heap usage: 1 allocs, 1 frees, 20 bytes allocated
==2955== 
==2955== All heap blocks were freed -- no leaks are possible
==2955== 
==2955== For counts of detected and suppressed errors, rerun with: -v
==2955== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

首先从“All heap blocks were freed -- no leaks are possible”可以看出上面的释放操作的确是正确的,而不是有些人认为的delete d;只会释放d[]的第一个元素的空间,后面的都不会得到释放。但是从“Mismatched free() / delete / delete []”知道Valgrind实际上是不允许这样操作的,虽然没有内存泄露问题,但是new[]与delete不匹配,这样的编程风格不经意间就容易犯低级错误,所以Valgrind报错了,但是我想Valgrind内部实现应该不会考虑的这么复杂,它就检查new是否与delete配对,new[]是否与delete[]配对,而不管有时候new[]与delete配对也不会出现问题的。

综上所述,给我的经验就是:在某些情况下,new[]分配的内存用delete不会出错,但是大多情况下会产生严重的内存问题,所以一定要养成将new和delete,new[]和delete[]配套使用的良好编程习惯。

 

2. 最看不懂的错误:一堆看不懂的Invalid read/write错误(更新:已解决)

比如下面这样一个程序:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include <stdio.h>  
  2. #include <string.h>  
  3. #include <stdlib.h>  
  4.   
  5. struct accept_pair {  
  6.   
  7.     bool is_accept_state;  
  8.   
  9.     bool is_strict_end;  
  10.   
  11.     char app_name[0];  
  12. };  
  13.   
  14. int main() {  
  15.       
  16.     char *s = "Alexia";  
  17.     accept_pair *ap = (accept_pair*)malloc(sizeof(accept_pair) + sizeof(s));  
  18.     strcpy(ap->app_name, s);  
  19.   
  20.     printf("app name: %s\n", ap->app_name);  
  21.   
  22.     free(ap);  
  23.   
  24.     return 0;  
  25. }  

首先对该程序做个扼要的说明:

这里结构体里定义零长数组的原因在于我的需求:我在其它地方要用到很大的accept_pair数组,其中只有个别accept_pair元素中的app_name是有效的(取决于某些值的判断,如果为true才给app_name赋值,如果为false则app_name无意义,为空),因此若是char app_name[20],那么大部分accept_pair元素都浪费了这20个字节的空间,所以我在这里先一个字节都不分配,到时谁需要就给谁分配,遵循“按需分配”的古老思想。可能有人会想,用char *app_name也可以啊,同样能实现按需分配,是的,只是多4个字节而已,属于替补方法。

在g++下经过测试,没有什么问题,能够正确运行,但用Valgrind检测时却报出了一些错误,不是内存泄露问题,而是内存读写错误:

==3511== Memcheck, a memory error detector
==3511== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==3511== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==3511== Command: ./zero
==3511== 
==3511== Invalid write of size 1
==3511==    at 0x402CD8B: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3511==    by 0x80484E3: main (in /home/hadoop/test/zero)
==3511==  Address 0x420002e is 0 bytes after a block of size 6 alloc'd
==3511==    at 0x402C418: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3511==    by 0x80484C8: main (in /home/hadoop/test/zero)
==3511== 
==3511== Invalid write of size 1
==3511==    at 0x402CDA5: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3511==    by 0x80484E3: main (in /home/hadoop/test/zero)
==3511==  Address 0x4200030 is 2 bytes after a block of size 6 alloc'd
==3511==    at 0x402C418: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3511==    by 0x80484C8: main (in /home/hadoop/test/zero)
==3511== 
==3511== Invalid read of size 1
==3511==    at 0x40936A5: vfprintf (vfprintf.c:1655)
==3511==    by 0x409881E: printf (printf.c:34)
==3511==    by 0x4063934: (below main) (libc-start.c:260)
==3511==  Address 0x420002e is 0 bytes after a block of size 6 alloc'd
==3511==    at 0x402C418: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3511==    by 0x80484C8: main (in /home/hadoop/test/zero)
==3511== 
==3511== Invalid read of size 1
==3511==    at 0x40BC3C0: _IO_file_xsputn@@GLIBC_2.1 (fileops.c:1311)
==3511==    by 0x4092184: vfprintf (vfprintf.c:1655)
==3511==    by 0x409881E: printf (printf.c:34)
==3511==    by 0x4063934: (below main) (libc-start.c:260)
==3511==  Address 0x420002f is 1 bytes after a block of size 6 alloc'd
==3511==    at 0x402C418: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3511==    by 0x80484C8: main (in /home/hadoop/test/zero)
==3511== 
==3511== Invalid read of size 1
==3511==    at 0x40BC3D7: _IO_file_xsputn@@GLIBC_2.1 (fileops.c:1311)
==3511==    by 0x4092184: vfprintf (vfprintf.c:1655)
==3511==    by 0x409881E: printf (printf.c:34)
==3511==    by 0x4063934: (below main) (libc-start.c:260)
==3511==  Address 0x420002e is 0 bytes after a block of size 6 alloc'd
==3511==    at 0x402C418: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3511==    by 0x80484C8: main (in /home/hadoop/test/zero)
==3511== 
==3511== Invalid read of size 4
==3511==    at 0x40C999C: __GI_mempcpy (mempcpy.S:59)
==3511==    by 0x40BC310: _IO_file_xsputn@@GLIBC_2.1 (fileops.c:1329)
==3511==    by 0x4092184: vfprintf (vfprintf.c:1655)
==3511==    by 0x409881E: printf (printf.c:34)
==3511==    by 0x4063934: (below main) (libc-start.c:260)
==3511==  Address 0x420002c is 4 bytes inside a block of size 6 alloc'd
==3511==    at 0x402C418: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3511==    by 0x80484C8: main (in /home/hadoop/test/zero)
==3511== 
app name: Alexia
==3511== 
==3511== HEAP SUMMARY:
==3511==     in use at exit: 0 bytes in 0 blocks
==3511==   total heap usage: 1 allocs, 1 frees, 6 bytes allocated
==3511== 
==3511== All heap blocks were freed -- no leaks are possible
==3511== 
==3511== For counts of detected and suppressed errors, rerun with: -v
==3511== ERROR SUMMARY: 9 errors from 6 contexts (suppressed: 0 from 0)
从检测报告可以看出:

strcpy(ap->app_name, s);这句是内存写错误,printf("app name: %s\n", ap->app_name);这句是内存读错误,两者都说明Valgrind认为ap->app_name所处内存空间是不合法的,可是我明明已经为其分配了内存空间,只是没有注明这段空间就是给它用的,难道结构体中零长数组char app_name[0]是不能写入值的吗?还是我对零长数组的使用有误?至今仍不得解,求大神解答……

------------------------------------------------------------------------------------------------------------------------------

更新谢谢博客园网友@shines77的好心指正,这里犯了个超级低级的错误,就是忘了main中s是char*的,因此sizeof(s)=4或8(64位机),因此accept_pair *ap = (accept_pair*)malloc(sizeof(accept_pair) + sizeof(s));这句并没有为app_name申请足够的空间,当然就会出现Invalid read/write了。这个低级错误真是。。。后来想了下,是自己在项目中直接拷贝过来的这句,项目中的s不是char*的,拷贝过来忘了改成accept_pair *ap = (accept_pair*)malloc(sizeof(accept_pair) + strlen(s) + 1);了,以后还是细心的好,真是浪费自己时间也浪费大家时间了。

 

3. 最不明所以的内存泄露:definitely lost/indefinitely lost(更新:已解决

请看下面这样一个程序:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include <stdio.h>  
  2. #include <string.h>  
  3.   
  4. class accept_pair {  
  5. public:  
  6.   
  7.     bool is_accept_state;  
  8.   
  9.     bool is_strict_end;  
  10.   
  11.     char *app_name;  
  12.   
  13. public:  
  14.   
  15.     accept_pair(bool is_accept = falsebool is_end = false);  
  16.   
  17.     ~accept_pair();  
  18. };  
  19.   
  20. class DFA {  
  21.   
  22. public:  
  23.   
  24.     unsigned int _size;  
  25.   
  26.     accept_pair **accept_states;  
  27.   
  28. public:  
  29.   
  30.     DFA(int size);  
  31.   
  32.     ~DFA();  
  33.   
  34.     void add_state(int index, char *s);  
  35.     void add_size(int size);  
  36. };  
  37.   
  38. int main() {  
  39.     char *s = "Alexia";  
  40.       
  41.     DFA *dfa = new DFA(3);  
  42.     dfa->add_state(0, s);  
  43.     dfa->add_state(1, s);  
  44.     dfa->add_state(2, s);  
  45.   
  46.     dfa->add_size(2);  
  47.     dfa->add_state(3, s);  
  48.     dfa->add_state(4, s);  
  49.   
  50.     printf("\napp_name: %s\n", dfa->accept_states[4]->app_name);  
  51.     printf("size: %d\n\n", dfa->_size);  
  52.   
  53.     delete dfa;  
  54.   
  55.     return 0;  
  56. }  
  57.   
  58. accept_pair::accept_pair(bool is_accept, bool is_end) {  
  59.     is_accept_state = is_accept;  
  60.     is_strict_end = is_end;  
  61.     app_name = NULL;  
  62. }  
  63.   
  64. accept_pair::~accept_pair() {   
  65.     if (app_name) {  
  66.         printf("delete accept_pair.\n");  
  67.         delete[] app_name;  
  68.     }  
  69. }  
  70.   
  71. DFA::DFA(int size) {  
  72.     _size = size;  
  73.   
  74.     accept_states = new accept_pair*[_size];  
  75.     for (int s = 0; s < _size; s++) {  
  76.         accept_states[s] = NULL;  
  77.     }  
  78. }  
  79.   
  80. DFA::~DFA() {  
  81.     for (int i = 0; i < _size; i++) {  
  82.         if (accept_states[i]) {  
  83.             printf("delete dfa.\n");  
  84.             delete accept_states[i];  
  85.             accept_states[i] = NULL;  
  86.         }  
  87.     }  
  88.     delete[] accept_states;  
  89. }  
  90.   
  91. void DFA::add_state(int index, char *s) {  
  92.     accept_states[index] = new accept_pair(truetrue);  
  93.     accept_states[index]->app_name = new char[strlen(s) + 1];  
  94.     memcpy(accept_states[index]->app_name, s, strlen(s) + 1);  
  95. }  
  96.   
  97. void DFA::add_size(int size) {  
  98.     // reallocate memory for accept_states.  
  99.     accept_pair **tmp_states = new accept_pair*[size + _size];  
  100.     for (int s = 0; s < size + _size; s++)  
  101.         tmp_states[s] = new accept_pair(falsefalse);  
  102.   
  103.     for (int s = 0; s < _size; s++) {  
  104.         tmp_states[s]->is_accept_state = accept_states[s]->is_accept_state;  
  105.         tmp_states[s]->is_strict_end = accept_states[s]->is_strict_end;  
  106.         if (accept_states[s]->app_name != NULL) {  
  107.             tmp_states[s]->app_name = new char[strlen(accept_states[s]->app_name) + 1];  
  108.             memcpy(tmp_states[s]->app_name, accept_states[s]->app_name, strlen(accept_states[s]->app_name) + 1);  
  109.         }  
  110.     }  
  111.   
  112.     // free old memory.  
  113.     for (int s = 0; s < _size; s++) {  
  114.         if (accept_states[s] != NULL) {  
  115.             delete accept_states[s];  
  116.             accept_states[s] = NULL;  
  117.         }  
  118.     }  
  119.     _size += size;  
  120.     delete []accept_states;  
  121.   
  122.     accept_states = tmp_states;  
  123. }  

虽然有点长,但逻辑很简单,其中add_size()首先分配一个更大的accept_pair数组,将已有的数据全部拷贝进去,然后释放掉原来的accept_pair数组所占空间,最后将旧的数组指针指向新分配的内存空间。这是个demo程序,在我看来这段程序是没有任何内存泄露问题的,因为申请的所有内存空间最后都会在DFA析构函数中得到释放。但是Valgrind的检测报告却报出了1个内存泄露问题(红色的是程序输出):

==3093== Memcheck, a memory error detector
==3093== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==3093== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==3093== Command: ./test
==3093== 
delete accept_pair.
delete accept_pair.
delete accept_pair.

app_name: Alexia
size: 5

delete dfa.
delete accept_pair.
delete dfa.
delete accept_pair.
delete dfa.
delete accept_pair.
delete dfa.
delete accept_pair.
delete dfa.
delete accept_pair.
==3093== 
==3093== HEAP SUMMARY:
==3093==     in use at exit: 16 bytes in 2 blocks
==3093==   total heap usage: 21 allocs, 19 frees, 176 bytes allocated
==3093== 
==3093== 16 bytes in 2 blocks are definitely lost in loss record 1 of 1
==3093==    at 0x402BE94: operator new(unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3093==    by 0x8048A71: DFA::add_size(int) (in /home/hadoop/test/test)
==3093==    by 0x8048798: main (in /home/hadoop/test/test)
==3093== 
==3093== LEAK SUMMARY:
==3093==    definitely lost: 16 bytes in 2 blocks
==3093==    indirectly lost: 0 bytes in 0 blocks
==3093==      possibly lost: 0 bytes in 0 blocks
==3093==    still reachable: 0 bytes in 0 blocks
==3093==         suppressed: 0 bytes in 0 blocks
==3093== 
==3093== For counts of detected and suppressed errors, rerun with: -v
==3093== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

说明add_size()这个函数里存在用new申请的内存空间没有得到释放,这一点感觉很费解,开始以为tmp_states指针所指向的数据赋给accept_states后没有及时释放导致的,于是我最后加了句delete tmp_states;结果招致更多的错误。相信不是Valgrind误报,说明我对C++的new和delete机制还是不明不白,一些于我而言不明所以的内存泄露问题真心不得解,希望有人能够告诉我是哪里的问题?

------------------------------------------------------------------------------------------------------------------------------

更新谢谢博客园好心网友@NewClear的解惑。这里的确有泄露问题,下面是他的解答:

第3个问题,是有两个泄露
DFA::add_state里面直接
accept_states[index] = new accept_pair(true, true);
如果原来的accept_states[index]不为NULL就泄露了
而在DFA::add_size里面,
for (int s = 0; s < size + _size; s++)
            tmp_states[s] = new accept_pair(false, false);
对新分配的tmp_states的每一个元素都new了一个新的accept_pair
所以在main函数里面dfa->add_size(2);以后,总共有5个成员,而且5个都不为NULL
之后
dfa->add_state(3, s);
dfa->add_state(4, s);
结果就导致了index为3和4的原先的对象泄露了
你的系统是32位的,所以一个accept_pair大小是8byte,两个对象就是16byte

解决方案也很简单,修改add_size函数,重新申请空间时仅为已有的accept_pair数据申请空间,其它的初始化为NULL,这样在需要时才在add_state里面申请空间,也就是修改add_size函数如下:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void DFA::add_size(int size) {  
  2.     // reallocate memory for accept_states.  
  3.     accept_pair **tmp_states = new accept_pair*[size + _size];  
  4.     for (int s = 0; s < size + _size; s++)  
  5.         tmp_states[s] = NULL;  
  6.   
  7.     for (int s = 0; s < _size; s++) {  
  8.         tmp_states[s] = new accept_pair(falsefalse);  
  9.         tmp_states[s]->is_accept_state = accept_states[s]->is_accept_state;  
  10.         tmp_states[s]->is_strict_end = accept_states[s]->is_strict_end;  
  11.         if (accept_states[s]->app_name != NULL) {  
  12.             tmp_states[s]->app_name = new char[strlen(accept_states[s]->app_name) + 1];  
  13.             memcpy(tmp_states[s]->app_name, accept_states[s]->app_name, strlen(accept_states[s]->app_name) + 1);  
  14.         }  
  15.     }  
  16.   
  17.     // free old memory.  
  18.     for (int s = 0; s < _size; s++) {  
  19.         if (accept_states[s] != NULL) {  
  20.             delete accept_states[s];  
  21.             accept_states[s] = NULL;  
  22.         }  
  23.     }  
  24.     _size += size;  
  25.     delete[]accept_states;  
  26.   
  27.     accept_states = tmp_states;  
  28. }  

4. 参考文献

(1) 如何使用Valgrind memcheck工具进行C/C++的内存泄漏检测 如何使用Valgrind memcheck工具进行C/C++的内存泄漏检测

(2)valgrind 详细说明

(3) 关于new和delete,new[] 和delete[]

(4)浅谈 C++ 中的 new/delete 和 new[]/delete[]



如何使用Valgrind memcheck工具进行C/C++的内存泄漏检测

英文原文:How to Detect Memory Leaks Using Valgrind memcheck Tool for C / C++

标签:  Valgrind
184人收藏此文章, 我要收藏 Dyllian 推荐于 8个月前 (共 6 段, 翻译完成于 10-09) ( 13评
参与翻译(3人)

系统编程中一个重要的方面就是有效地处理与内存相关的问题。你的工作越接近系统,你就需要面对越多的内存问题。有时这些问题非常琐碎,而更多时候它会演变成一个调试内存问题的恶梦。所以,在实践中会用到很多工具来调试内存问题。

在本文中,我们将讨论最流行的开源内存管理框架 VALGRIND。

摘自 Valgrind.org:

Valgrind是用于构建动态分析工具的探测框架。它包括一个工具集,每个工具执行某种类型的调试、分析或类似的任务,以帮助完善你的程序。Valgrind的架构是模块化的,所以可以容易地创建新的工具而又不会扰乱现有的结构。

mingshun
mingshun
翻译于 7个月前

1人顶

 翻译的不错哦!

许多有用的工具被作为标准而提供。

  1. Memcheck是一个内存错误检测器。它有助于使你的程序,尤其是那些用C和C++写的程序,更加准确。
  2. Cachegrind是一个缓存和分支预测分析器。它有助于使你的程序运行更快。
  3. Callgrind是一个调用图缓存生成分析器。它与Cachegrind的功能有重叠,但也收集Cachegrind不收集的一些信息。
  4. Helgrind是一个线程错误检测器。它有助于使你的多线程程序更加准确。
  5. DRD也是一个线程错误检测器。它和Helgrind相似,但使用不同的分析技术,所以可能找到不同的问题。
  6. Massif是一个堆分析器。它有助于使你的程序使用更少的内存。
  7. DHAT是另一种不同的堆分析器。它有助于理解块的生命期、块的使用和布局的低效等问题。
  8. SGcheck是一个实验工具,用来检测堆和全局数组的溢出。它的功能和Memcheck互补:SGcheck找到Memcheck无法找到的问题,反之亦然。
  9. BBV是个实验性质的SimPoint基本块矢量生成器。它对于进行计算机架构的研究和开发很有用处。

也有一些对大多数用户没有用的小工具:Lackey是演示仪器基础的示例工具;Nulgrind是一个最小化的Valgrind工具,不做分析或者操作,仅用于测试目的。

在这篇文章我们将关注“memcheck”工具。

Ley
Ley
翻译于 7个月前

1人顶

 翻译的不错哦!

使用 Valgrind Memcheck

memcheck工具的使用方式如下:

1 valgrind --tool=memcheck ./a.out

从上面的命令可以清楚的看到, 主要的命令是valgrind,而我们想使用的工具是通过'-tool'选项来指定的. 上面的‘a.out’指的是我们想使用memcheck运行的可执行文件.

该工具可以检测下列与内存相关的问题 :

  • 未释放内存的使用
  • 对释放后内存的读/写
  • 对已分配内存块尾部的读/写
  • 内存泄露
  • 不匹配的使用malloc/new/new[] 和 free/delete/delete[]
  • 重复释放内存

注意: 上面列出的并不很全面,但却包含了能被该工具检测到的很多普遍的问题.

让我们一个一个地对上面的场景进行讨论:

注意: 下面讨论的所有测试代码都应该使用gcc并且加上-g选项(用来在memcheck的输出中生成行号)进行编译. 就想我们之前讨论过的 C程序被编译成可执行文件, 它需要经历四个不同的阶段.

ToB蓝波湾
ToB蓝波湾
翻译于 7个月前

0人顶

 翻译的不错哦!

1. 使用未初始化的内存

Code :

01 #include <stdio.h>
02 #include <stdlib.h>
03  
04 int main(void)
05 {
06     char*p;
07  
08     charc = *p;
09  
10     printf("\n [%c]\n",c);
11  
12     return 0;
13 }

在上面的代码中,我们尝试使用未初始化的指针 ‘p’.

让我们运行Memcheck来看下结果.

01 $ valgrind --tool=memcheck ./val
02 ==2862== Memcheck, a memory error detector
03 ==2862== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
04 ==2862== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
05 ==2862== Command: ./val
06 ==2862==
07 ==2862== Use of uninitialised value of size 8
08 ==2862==    at 0x400530: main (valgrind.c:8)
09 ==2862==
10  
11 [#]
12 ==2862==
13 ==2862== HEAP SUMMARY:
14 ==2862==     in use at exit: 0 bytes in 0 blocks
15 ==2862==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
16 ==2862==
17 ==2862== All heap blocks were freed -- no leaks are possible
18 ==2862==
19 ==2862== For counts of detected and suppressed errors, rerun with: -v
20 ==2862== Use --track-origins=yes to see where uninitialized values come from
21 ==2862== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)

从上面的输出可以看到,Valgrind检测到了未初始化的变量,然后给出了警告(上面加粗的几行(译者注:貌似上面没有加粗的)).

2. 在内存被释放后进行读/写

Code :

01 #include <stdio.h>
02 #include <stdlib.h>
03  
04 int main(void)
05 {
06     char *p = malloc(1);
07     *p = 'a';
08  
09     charc = *p;
10  
11     printf("\n [%c]\n",c);
12  
13     free(p);
14     c = *p;
15     return 0;
16 }

上面的代码中,我们有一个释放了内存的指针 ‘p’ 然后我们又尝试利用指针获取值.

让我们运行memcheck来看一下Valgrind对这种情况是如何反应的.

01 $ valgrind --tool=memcheck ./val
02 ==2849== Memcheck, a memory error detector
03 ==2849== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
04 ==2849== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
05 ==2849== Command: ./val
06 ==2849==
07  
08  [a]
09 ==2849== Invalid read of size 1
10 ==2849==    at 0x400603: main (valgrind.c:30)
11 ==2849==  Address 0x51b0040 is 0 bytes inside a block of size 1 free'd
12 ==2849==    at 0x4C270BD: free (vg_replace_malloc.c:366)
13 ==2849==    by 0x4005FE: main (valgrind.c:29)
14 ==2849==
15 ==2849==
16 ==2849== HEAP SUMMARY:
17 ==2849==     in use at exit: 0 bytes in 0 blocks
18 ==2849==   total heap usage: 1 allocs, 1 frees, 1 bytes allocated
19 ==2849==
20 ==2849== All heap blocks were freed -- no leaks are possible
21 ==2849==
22 ==2849== For counts of detected and suppressed errors, rerun with: -v
23 ==2849== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)

从上面的输出内容可以看到,Valgrind检测到了无效的读取操作然后输出了警告 ‘Invalid read of size 1′.

另注,使用gdb来调试c程序.

3. 从已分配内存块的尾部进行读/写

Code :

01 #include <stdio.h>
02 #include <stdlib.h>
03  
04 int main(void)
05 {
06     char *p = malloc(1);
07     *p = 'a';
08  
09     charc = *(p+1);
10  
11     printf("\n [%c]\n",c);
12  
13     free(p);
14     return 0;
15 }

在上面的代码中,我们已经为‘p’分配了一个字节的内存,但我们在将值读取到 ‘c’中的时候使用的是地址p+1.

现在我们使用Valgrind运行上面的代码 :

01 $ valgrind --tool=memcheck ./val
02 ==2835== Memcheck, a memory error detector
03 ==2835== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
04 ==2835== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
05 ==2835== Command: ./val
06 ==2835==
07 ==2835== Invalid read of size 1
08 ==2835==    at 0x4005D9: main (valgrind.c:25)
09 ==2835==  Address 0x51b0041 is 0 bytes after a block of size 1 alloc'd
10 ==2835==    at 0x4C274A8: malloc (vg_replace_malloc.c:236)
11 ==2835==    by 0x4005C5: main (valgrind.c:22)
12 ==2835==
13  
14  []
15 ==2835==
16 ==2835== HEAP SUMMARY:
17 ==2835==     in use at exit: 0 bytes in 0 blocks
18 ==2835==   total heap usage: 1 allocs, 1 frees, 1 bytes allocated
19 ==2835==
20 ==2835== All heap blocks were freed -- no leaks are possible
21 ==2835==
22 ==2835== For counts of detected and suppressed errors, rerun with: -v
23 ==2835== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)

同样,该工具在这种情况下也检测到了无效的读取操作.

4. 内存泄露

Code:

01 #include <stdio.h>
02 #include <stdlib.h>
03  
04 int main(void)
05 {
06     char *p = malloc(1);
07     *p = 'a';
08  
09     charc = *p;
10  
11     printf("\n [%c]\n",c);
12  
13     return 0;
14 }

在这次的代码中, 我们申请了一个字节但是没有将它释放.现在让我们运行Valgrind看看会发生什么:

01 $ valgrind --tool=memcheck --leak-check=full ./val
02 ==2888== Memcheck, a memory error detector
03 ==2888== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
04 ==2888== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
05 ==2888== Command: ./val
06 ==2888==
07  
08  [a]
09 ==2888==
10 ==2888== HEAP SUMMARY:
11 ==2888==     in use at exit: 1 bytes in 1 blocks
12 ==2888==   total heap usage: 1 allocs, 0 frees, 1 bytes allocated
13 ==2888==
14 ==2888== 1 bytes in 1 blocks are definitely lost in loss record 1 of 1
15 ==2888==    at 0x4C274A8: malloc (vg_replace_malloc.c:236)
16 ==2888==    by 0x400575: main (valgrind.c:6)
17 ==2888==
18 ==2888== LEAK SUMMARY:
19 ==2888==    definitely lost: 1 bytes in 1 blocks
20 ==2888==    indirectly lost: 0 bytes in 0 blocks
21 ==2888==      possibly lost: 0 bytes in 0 blocks
22 ==2888==    still reachable: 0 bytes in 0 blocks
23 ==2888==         suppressed: 0 bytes in 0 blocks
24 ==2888==
25 ==2888== For counts of detected and suppressed errors, rerun with: -v
26 ==2888== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)

输出行(上面加粗的部分)显示,该工具能够检测到内存的泄露.

注意: 在这里我们增加了一个选项‘–leak-check=full’来得到内存泄露的详细细节.

ToB蓝波湾
ToB蓝波湾
翻译于 7个月前

0人顶

 翻译的不错哦!

5. 不匹配地使用malloc/new/new[] 和 free/delete/delete[]

Code:

01 #include <stdio.h>
02 #include <stdlib.h>
03 #include<iostream>
04  
05 int main(void)
06 {
07     char *p = (char*)malloc(1);
08     *p = 'a';
09  
10     charc = *p;
11  
12     printf("\n [%c]\n",c);
13     delete p;
14     return 0;
15 }

上面的代码中,我们使用了malloc()来分配内存,但是使用了delete操作符来删除内存.

注意 : 使用g++来编译上面的代码,因为delete操作符是在C++中引进的,而要编译C++需要使用g++.

让我们运行来看一下 :

01 $ valgrind --tool=memcheck --leak-check=full ./val
02 ==2972== Memcheck, a memory error detector
03 ==2972== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
04 ==2972== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
05 ==2972== Command: ./val
06 ==2972==
07  
08  [a]
09 ==2972== Mismatched free() / delete delete []
10 ==2972==    at 0x4C26DCF: operator delete(void*) (vg_replace_malloc.c:387)
11 ==2972==    by 0x40080B: main (valgrind.c:13)
12 ==2972==  Address 0x595e040 is 0 bytes inside a block of size 1 alloc'd
13 ==2972==    at 0x4C274A8: malloc (vg_replace_malloc.c:236)
14 ==2972==    by 0x4007D5: main (valgrind.c:7)
15 ==2972==
16 ==2972==
17 ==2972== HEAP SUMMARY:
18 ==2972==     in use at exit: 0 bytes in 0 blocks
19 ==2972==   total heap usage: 1 allocs, 1 frees, 1 bytes allocated
20 ==2972==
21 ==2972== All heap blocks were freed -- no leaks are possible
22 ==2972==
23 ==2972== For counts of detected and suppressed errors, rerun with: -v
24 ==2972== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)

从上面的输出可以看到 (加粗的行), Valgrind清楚的说明了‘不匹配的使用了free() / delete / delete []‘

你可以尝试在测试代码中使用'new'和'free'进行组合来看看Valgrind给出的结果是什么.

ToB蓝波湾
ToB蓝波湾
翻译于 7个月前

2人顶

 翻译的不错哦!

6. 两次释放内存

Code :

01 #include <stdio.h>
02 #include <stdlib.h>
03  
04 int main(void)
05 {
06     char *p = (char*)malloc(1);
07     *p = 'a';
08  
09     char c = *p;
10     printf("\n [%c]\n",c);
11     free(p);
12     free(p);
13     return 0;
14 }

在上面的代码中, 我们两次释放了'p'指向的内存. 现在让我们运行memcheck :

01 $ valgrind --tool=memcheck --leak-check=full ./val
02 ==3167== Memcheck, a memory error detector
03 ==3167== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
04 ==3167== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
05 ==3167== Command: ./val
06 ==3167==
07  
08  [a]
09 ==3167== Invalid free() / delete delete[]
10 ==3167==    at 0x4C270BD: free (vg_replace_malloc.c:366)
11 ==3167==    by 0x40060A: main (valgrind.c:12)
12 ==3167==  Address 0x51b0040 is 0 bytes inside a block of size 1 free'd
13 ==3167==    at 0x4C270BD: free (vg_replace_malloc.c:366)
14 ==3167==    by 0x4005FE: main (valgrind.c:11)
15 ==3167==
16 ==3167==
17 ==3167== HEAP SUMMARY:
18 ==3167==     in use at exit: 0 bytes in 0 blocks
19 ==3167==   total heap usage: 1 allocs, 2 frees, 1 bytes allocated
20 ==3167==
21 ==3167== All heap blocks were freed -- no leaks are possible
22 ==3167==
23 ==3167== For counts of detected and suppressed errors, rerun with: -v
24 ==3167== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)

从上面的输出可以看到(加粗的行), 该功能检测到我们对同一个指针调用了两次释放内存操作.

在本文中,我们把注意力放在了内存管理框架Valgrind,然后使用memcheck(Valgrind框架提供的)工具来了解它是如何降低需要经常操作内存的程序员的负担的. 该工具能够检测到很多手动检测不到的与内存相关的问题

ToB蓝波湾
ToB蓝波湾
翻译于 7个月前

1人顶

 翻译的不错哦!


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值