雕刻时光

just do it……nothing impossible
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C++中内存泄露的检测

Posted on 2014-03-02 13:20  huhuuu  阅读(490)  评论(0编辑  收藏  举报

  C++没有java的内存垃圾回收机制,在程序短的时候可能比较容易发现问题,在程序长的时候是否有什么检测的方法呢?

  假设有一个函数可以某点检测程序的内存使用情况,那是否可以在程序开始的时候设置一个点,在程序结束的时候再设置一个点,比较这两个值是否一样就可以知道内存泄露的情况了。

  windows下的内存检测方法:

#define _CRTDBG_MAP_ALLOC //一定要加上这一句
#include <stdlib.h>
#include <crtdbg.h>

#include <iostream>
using namespace std;

_CrtMemState s1, s2, s3;

void GetMemory(char *p, int num)
{
    p = (char*)malloc(sizeof(char) * num);
}

int main(int argc,char** argv)
{
    _CrtMemCheckpoint( &s1 ); //检测当前内存的使用情况
    char *str = NULL;
    int n=1000;
    GetMemory(str, 100);//这里申请后没有释放内存,内存泄露了

    _CrtMemCheckpoint( &s2 ); 

    _CrtMemDifference( &s3, &s1, &s2); //比较s1,s2的内存差异,结果放s3
    printf("%ud",s3.lTotalCount);

    return 0;
}

 

之前一直没有搞清楚_CrtDumpMemoryLeaks();的调用方法,因为之前执行程序都是ctrl + F5的,原来发现这个函数是在F5的时候生效

#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK  new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif

int main()
{
    
    int* p = new int(); 
    int n=5;
    while(n--){
        new int;
    }
    _CrtDumpMemoryLeaks();

    return 0;
}

嗯,编译器提示有6个内存块内存泄露了。

同时,注意其中也显示了内存泄露的行号,利于调试。

 

在linux下也有类似的方法

参考:http://www.cnblogs.com/skynet/archive/2011/02/20/1959162.html