#include <iostream>
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#define new DEBUG_CLIENTBLOCK
#endif
void test_c()
{
int* p = (int*)malloc(10 * sizeof(int));
//free(p);
}
void test_cpp()
{
int* p = new int[10];
//delete [] p;
}
int main()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);//_CrtDumpMemoryLeaks();
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);
test_c();
test_cpp();
std::cout << "ok" << std::endl;
}
在输出--调试窗口会有信息:
Detected memory leaks!
Dumping objects ->
F:\Cpp\MemoryLeak\MemoryLeak.cpp(25) : {156} client block at 0x00F85A40, subtype 0, 40 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
{155} normal block at 0x00F80580, 40 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
显示第25行有内存泄漏,但是第18行也有内存泄漏,但是没有明确的行和文件名的信息,还要研究一下为啥,c语言的没支持好~
定义了宏_CRTDBG_MAP_ALLOC会使用dbgmalloc代替malloc,使用new( _CLIENT_BLOCK, __FILE__, __LINE__)代替new,就是在里面追加了行号和文件名的信息,定位到内存泄漏的位置的。
MICROSOFT的官方文档有比较详细的介绍: