admin管理员组

文章数量:1531715

一.   Memcheck 工具介绍

valgrind 工具集包括各种工具,每个工具分别调试代码中不同类型的 bug。其中,Memcheck 工具为定位内存泄露或内存溢出等内存方面的问题。

二.  Memcheck 工具使用

下面来说明 Memcheck 工具定位代码中存在的内存泄露等内存相关问题。以下面代码为实例:

#include <stdio.h>
#include <stdlib.h>
 
void fun(void) 
{
    char *p = malloc(10*sizeof(char));
    p[10] = 0; //问题1:堆块溢出
}              //问题2:内存泄漏--p未释放
 
int main(int argc, char **argv)
{ 
    fun() ;
    return 0 ;
}

下来使用 Memcheck 工具检测上面代码中存在的内存泄露或溢出等内存方面的问题。操作如下:

首先,编译程序,即输入 gcc -g main.c -o main.out 命令(带 -g 选项为了Memcheck 工具定位内存问题时可以定位到 C/C++的具体的某行);

其次, 使用 Memcheck 工具排查内存 bug。输入命令:valgrind --leak-check=yes ./main.out

操作如下所示:

分析以上打印 Log 信息,如下:

程序访问非法地址的内存,无效写入,即堆溢出。在代码的第 7 行。

==3492== Invalid write of size 1

==3492==    at 0x10916B: fun (main.c:7)

堆空间分配的情况如下:

==3492== HEAP SUMMARY:
==3492==     in use at exit: 10 bytes in 1 blocks
==3492==   total heap usage: 1 allocs, 0 frees, 10 bytes allocated

内存泄漏的 Log 信息,内存泄露问题出现在第 6 行,如下所示:

==3492== 10 bytes in 1 blocks are definitely lost in loss record 1 of 1
==3492==    at 0x483C855: malloc (vg_replace_malloc.c:393)
==3492==    by 0x10915E: fun (main.c:6)
==3492==    by 0x109188: main (main.c:12)

有几种泄漏:其中有两个最重要的类别。分别是 definitely lost肯定泄露) 与 possibly lost(可能已经泄露)。代码中内存泄露统计如下:

==3492== LEAK SUMMARY:
==3492==    definitely lost: 10 bytes in 1 blocks
==3492==    indirectly lost: 0 bytes in 0 blocks
==3492==      possibly lost: 0 bytes in 0 blocks
==3492==    still reachable: 0 bytes in 0 blocks
==3492==         suppressed: 0 bytes in 0 blocks

可以看出,代码中存在 10 字节的内存泄露。

本文标签: 内存工具方法Linuxvalgrind