在Linux平台中调试C/C++内存泄漏方法 (腾讯和MTK面试的时候问到的)

 

#include <string.h>
#include <stdlib.h>
int LeakTest(char * Para)
{
if(NULL==Para){
//local_log(“LeakTest Func: empty parameter/n”);
return -1;
}
char * Logmsg = new char[128];
if(NULL == Logmsg){
//local_log(“memeory allocation failed/n”);
return -2;
}
sprintf(Logmsg,”LeakTest routine exit: ‘%s’./n”, Para);
//local_log(Logmsg);
return 0;
}
int main(int argc,char **argv )
{
char szInit [] = “testcase1”;
LeakTest(szInit);
return 0;
}

Linux x86 (glibc 2.2.4)

  • Linux s390/s390x (glibc 2.3.3 or higher)
  • Linux (PowerPC, USS) (glibc 2.3.2 or higher)
  • AIX (4.3.2+)
  • Window2000 以上
  • ^
    BEAM_VERSION=3.4.2
    BEAM_ROOT=/home/hanzb/memdetect
    BEAM_DIRECTORY_WRITE_INNOCENTS=
    BEAM_DIRECTORY_WRITE_ERRORS=
    — ERROR23(heap_memory) /*memory leak*/ >>>ERROR23_LeakTest_7b00071dc5cbb458
    “code2.cpp”, line 24: memory leak
    ONE POSSIBLE PATH LEADING TO THE ERROR:
    “code2.cpp”, line 22: allocating using `operator new[]’ (this memory will not be freed)
    “code2.cpp”, line 22: assigning into `Logmsg’
    “code2.cpp”, line 24: deallocating `Logmsg’ because exiting its scope (losing last pointer to the memory)
    — ERROR1 /*uninitialized*/ >>>ERROR1_foo_60c7889b2b608
    “code2.cpp”, line 16: uninitialized `c’
    ONE POSSIBLE PATH LEADING TO THE ERROR:
    “code2.cpp”, line 10: allocating `c’
    “code2.cpp”, line 13: the if-condition is false
    “code2.cpp”, line 16: getting the value of `c’
    VALUES AT THE END OF THE PATH:
    p != 0 — ERROR2 /*operating on NULL*/ >>>ERROR2_foo_af57809a2b615
    “code2.cpp”, line 17: invalid operation involving NULL pointer
    ONE POSSIBLE PATH LEADING TO THE ERROR:
    “code2.cpp”, line 13: the if-condition is true (used as evidence that error is possible)
    “code2.cpp”, line 16: the if-condition is true
    “code2.cpp”, line 17: invalid operation `[]’ involving NULL pointer `p’
    VALUES AT THE END OF THE PATH:
    c = 1 p = 0 a <= 0

     

     

    读写已经释放的内存

  • 读写内存块越界(从前或者从后)
  • 使用还未初始化的变量
  • 将无意义的参数传递给系统调用
  • 内存泄漏
  •  

    如果我在此介绍的三款工具你都不喜欢,那也没有关系,可在下面站点中找到很多检测内存错误的工具:http://www.sslug.dk /emailarkiv/bog/2001_08/msg00030.html。此外,还有一些商业工具,比如Purify、Geodesic等。在此就 不详细介绍。

    文章知识点与官方知识档案匹配,可进一步学习相关知识C技能树首页概览113152 人正在系统学习中

    来源:wuChen4646

    声明:本站部分文章及图片转载于互联网,内容版权归原作者所有,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!

    上一篇 2015年2月26日
    下一篇 2015年2月26日

    相关推荐