Linux平台下检测、调试C/C++程序内存泄漏
Linux平台下检测、调试C/C++程序内存泄漏
1.Linux平台下 如何发现内存泄漏
ps -aux
2. 静态分析
**2.1 手动检测**
- #include<stdio.h>
- #include<string.h>
- #include<stdlib.h>
- intLeakTest(char*Para)
- {
- if(NULL==Para)
- {
- //local_log("LeakTest Func: empty parameter\n");
- return-1;
- }
- char*Logmsg=newchar[128];
- if(NULL ==Logmsg)
- {
- //
- local_log("memeory allocation failed\n");
- return-2;
- }
- sprintf(Logmsg,"LeakTest routine exit: '%s'.\n",Para);
- local_log(Logmsg);return0;
- }
- int main(int argc,char**argv )
- {
- char szInit []="testcase1";
- LeakTest(szInit);
- return0;
- }
-
**2.2 静态代码分析工具**
代码静态扫描和分析的工具比较多,比如 splint, PC-LINT, BEAM 等。因为 BEAM 支持的平台比较多,这以 BEAM 为例,做个简单介绍,其它有类似的处理过程。BEAM 可以检测四类问题: 没有初始化的变量;废弃的空指针;内存泄漏;冗余计算。而且支持的平台比较多。
- #include<stdio.h>
- #include<string.h>
- #include<stdlib.h>
- int*p;
- void foo(int a)
- {
- int b, c; b =0;
- if(!p)
- c =1;
- if(c > a)
- c += p[1];
- }
- intLeakTest(char*Para)
- {
- char*Logmsg=newchar[128];
- if((Para==NULL)||(Logmsg== NULL))
- return-1;
- sprintf(Logmsg,"LeakTest routine exit: '%s'.\n",Para);
- return0;
- }
- int main(int argc,char**argv )
- {
- char szInit []="testcase1";
- LeakTest(szInit);
- return0;
- }
-
**2.3 内嵌程序**
可以重载内存分配和释放函数 new 和 delete,然后编写程序定期统计内存的分配和释放,从中找出可能的内存泄漏。或者调用系统函数定期监视程序堆的大小,关键要确定堆的增长是泄漏而不是合理的内存使用。这类方法比较复杂,在这就不给出详细例子了。
|
评论暂时关闭