使用mtrace()函数检内存溢出

来源:互联网 发布:中国武术 知乎 编辑:程序博客网 时间:2024/04/26 02:51

对于内存溢出之类的麻烦可能大家在编写指针比较多的复杂的程序的时候就会遇到。Linux系统下有一个工具可以帮忙调试,这就是mtrace。mtrace主要能够检测一些内存分配和泄漏的失败等。下面我们来学习一下它的用法(man mtrace)

1.在需要跟踪的程序中需要包含头文件<mcheck.h>,而且在main()函数的最开始包含一个函数调用mtrace()。由于在 main函数的最开头调用了mtrace(),所以该进程后面的一切分配和释放内存的操作都可以由mtrace来跟踪和分析。

2.定义一个环境变量,用来指定一个文件,该文件用来输出log信息。如下的例子:$export MALLOC_TRACE=mymemory.log

        这里也可以在程序中设置:setenv("MALLOC_TRACE", "mymemory.log", 1);此语句放在mtrace()前就可以.

3.正常运行程序,此时程序中的关于内存分配和释放的操作都可以记录下来

4.然后用mtrace使用工具来分析log文件。例如:$mtrace testmtrace $MALLOC_TRACE

   (其中testmtrace为可执行文件)

见例子:

#include <mcheck.h>#include <stdio.h>#include <stdlib.h>int main(){        char *hello;        mtrace();        hello = (char*)malloc(20);        sprintf(hello, "hello world!");        return 1;}
shang@ubuntu:~/Cpro$ gcc testmtrace.c -o testmtrace
shang@ubuntu:~/Cpro$ ./testmtrace
shang@ubuntu:~/Cpro$ mtrace testmtrace mytrace.log

Memory not freed:
-----------------
   Address     Size     Caller
0x092aa378     0x14  at 0x804846e                                            这是 产生界过,显示内存没有被释放.

改动一下程序:

#include <mcheck.h>#include <stdio.h>#include <stdlib.h>int main(){        char *hello;        mtrace();        hello = (char*)malloc(20);        sprintf(hello, "hello world!");        free(hello);                  //新增释放内存        return 1;}
shang@ubuntu:~/Cpro$ gcc testmtrace.c -o testmtrace
shang@ubuntu:~/Cpro$ ./testmtrace
shang@ubuntu:~/Cpro$ mtrace testmtrace mytrace.log
No memory leaks.                                                                                   结果是没有内存leak


附:setenv()函数说明.

setenv(改变或增加环境变量)
相关函数 getenv,putenv,unsetenv
表头文件 : #include<stdlib.h>
定义函数 : int setenv(const char *name, const char * value,int overwrite);
函数说明 : setenv()用来改变或增加环境变量的内容。参数name为环境变量名称字符串。
参数 : value则为变量内容,参数overwrite用来决定是否要改变已存在的环境变量。如果overwrite不为0,而该环境变量原已有内容,则原内容会被改为参数value所指的变量内容。如果overwrite为0,且该环境变量已有内容,则参数value会被忽略。
返回值 : 执行成功则返回0,有错误发生时返回-1。

原创粉丝点击