loc
#define malloc(s) dbg_malloc(s, __FILE__, __LINE__)
// instead of calloc
#define calloc(c, s) dbg_calloc(c, s, __FILE__, __LINE__)
// instead of free
#define free(p) dbg_free(p)
/**
* allocation memory
*/
void *dbg_malloc(size_t elem_size, char *filename, size_t line);
/**
* allocation and zero memory
*/
void *dbg_calloc(size_t count, size_t elem_size, char *filename, size_t line);
/**
* deallocate memory
*/
void dbg_free(void *ptr);
/**
* show memory leake report
*/
void show_block();
#endif // _MEM_CHECK_H
使用的时候只需要包含上述头文件(例如命名为memcheck.h),并将上述C文件引入到项目中即可。测试代码如下:
#ifdef DEBUG
#include "memcheck.h"
#endif
int main()
{
int* p;
#ifdef DEBUG
atexit(show_block); // 在程序结束后显示内存泄漏报告
#endif // DEBUG
// 分配内存并不回收,显示内存泄漏报告
p = (int*)malloc(1000);
return 0;
}
|