歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux平台下檢測、調試C/C++程序內存洩漏

Linux平台下檢測、調試C/C++程序內存洩漏

日期:2017/3/1 10:08:48   编辑:Linux編程

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,然後編寫程序定期統計內存的分配和釋放,從中找出可能的內存洩漏。或者調用系統函數定期監視程序堆的大小,關鍵要確定堆的增長是洩漏而不是合理的內存使用。這類方法比較復雜,在這就不給出詳細例子了。

Copyright © Linux教程網 All Rights Reserved