现在的位置: 首页 > 综合 > 正文

Google memchek 内存检测

2012年12月07日 ⁄ 综合 ⁄ 共 876字 ⁄ 字号 评论关闭

最近在看了一下内存检测,在http://code.google.com/p/memcheck/可以找到,文章有源码和test,简单的几句介绍,刚开始没怎么看懂,自己根据使用说明用了下立马就能上手,显示结果最好用cmd调用生成的exe,能清楚打印mem
leaking的情况。

主要代码:

bool mc_checkmem(){
bool memLeaked=false;
for(int i=0;i<MC_HASHTABLESIZE;++i){
mc_block_node_t* ptr=pTable[i];
if(ptr==NULL){
continue;
}
memLeaked=true;
while(ptr){
printf("Leaked object (size %u ",ptr->size);
#ifdef MC_ADDRESS
printf("at 0x%p ",(ptr+1));
#endif
#ifdef MC_FILENAME
printf("in %s",ptr->file);
#endif
#ifdef MC_FUNCTION
printf(":%s()",ptr->func);
#endif
#ifdef MC_LINE_NUMBER
printf(":%d",ptr->line);
#endif
printf(")\n");
ptr=ptr->next;
}
}
return memLeaked;
}

程序通过建立以个内存块的hash表,来记录内存的使用情况,并打印出来,结果很详细。本人建立一个DLL并加入了memcheck程序。DLL中内存泄漏代码如下:

double MyMathFuncs::Divide(double a,double b)
{
int* c=new int[10];
//printf("main():b==0x%p\n",b);
for(int i=0;i<10;++i){
c[i]=i;
}
if(b == 0)
{
throw new invalid_argument("b cannot be zero");
}

return a / b;
}

结果为:


程序清楚打印出是怎么分配内存,分配内存的大小,以及位置和内存泄漏的情况。

抱歉!评论已关闭.