mtrace查看内存使用情况

来源:互联网 发布:it人才市场 编辑:程序博客网 时间:2024/04/20 14:14

对于内存溢出之类的麻烦可能大家在编写指针比较多的复杂的程序的时候就会遇到。Debug起来也是比较累人。其实linux系统下有一个使用的工具可以帮忙来调试的,这就是mtrace。mtrace主要能够检测一些内存分配和泄漏的失败等。

函数原型如下:

    void mtrace(void);

    void muntrace(void);

    头文件为:mcheck.h

    用法:

   1. 首先确定需要检测那一段代码

   2. 然后再在这段代码的前面调用mtrace(),在这段代码之后调用muntrace()。

   3. 设置环境变量:MALLOC_TRACE,可以在程序编译好后通过命令:

      export MALLOC_TRACE=./testmtrace.log   //其中log是用来存放内存泄漏信息的日志文件名。

      也可以在调用mtrace()之前调用函数设置环境变量:setenv("MALLOC_TRACE", "testmtrace.log", 1);

   4. 编译并运行程序,这样内存泄漏信息就会写到log文件中。

   5. 查看log文件,如:cat testmtrace.log

注意: 一般情况下不要调用muntrace, 而让程序自然结束. 因为可能有些释放内存代码要到muntrace之后才运行.


下面我们看一个例子:

[hwang@langchao test]$ cat testmtrace.c
#include <stdio.h>
#include <stdlib.h>
#include <mcheck.h>

int main()
{
     {
          setenv("MALLOC_TRACE", "testmtrace.log", 1);//设置环境变量MALLOC_TRACE
          mtrace();    //在需要检测的代码段之前调用mtrace函数
     }

     char *hello;
     mtrace();
     hello = (char*) malloc(20);
     sprintf(hello,"\nhello world!");

     muntrace();      // 在需要检测的代码段之后调用muntrace函数,

     return 1;
}


[hwang@langchao test]$ gcc testmtrace.c -o testmtrace
[hwang@langchao test]$./testmtrace
[hwang@langchao test]$ mtrace testmtrace mytrace.log

Memory not freed:
-----------------
Address Size Caller
0x08049860 0x14 at /usr/src/build/53700-i386/BUILD/glibc-2.2.4/csu/init.c:0


当然,你也可以直接查看log文件其中“+”表示申请的内存,“-”表示释放的内存。

原创粉丝点击