在项目开发中,有的函数会被其他不同的函数经常调用,
然后发现死机问题,但又不清楚是谁调用后出现的,可以用下面的方法,用打印抓一下便知。
20150317改善版,内存泄漏检查工具:
#include
#includevoid *
debug_malloc(size_t size, const char *file, int line, const char *func)
{
void *p;p = malloc(size);
printf("%s:%d:%s:malloc(%ld): p=0x%lx\n",
file, line, func, size, (unsigned long)p);
return p;
}#define malloc(s) debug_malloc(s, __FILE__, __LINE__, __func__)
#define free(p) do { \
printf("%s:%d:%s:free(0x%lx)\n", __FILE__, __LINE__, \
__func__, (unsigned long)p); \
if(p){
free(p);
}
p = NULL;
} while (0)int
main(int argc, char *argv[])
{
char *p;
p = malloc(1024);
free(p);
return 0;
}
-----------------------------------------------------------------------------
int check_mem_overflow(int maxlen,int curlen,char * func) {if(curlen >= (maxlen - 1)){
printf("FIXME:%s is out of memory!\r\n",func);
return 0;
}
return 1;}
//使用举例
void fuction()
{……
check_mem_overflow(MAXLEN,strlen(str),__func__);
……
}