C++ windows 内存泄漏定位
使用<crtdbg.h>的接口来定位内存泄漏问题,请注意只能在Debug下进行调试,主要有如下接口:
_CrtDumpMemoryLeaks();//打印所有内存泄漏信息
_CrtMemDifference(&s3, &s1, &s2)//判断检监测点1和监测点2是否不同
_CrtMemDumpStatistics(&s3);//打印泄漏内存
代码如下:
#define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #include <iostream> void TestLeak() { char* p = new char[100]; } _CrtMemState s1, s2, s3; int main(int argc, char *argv[]) { _CrtMemCheckpoint(&s1);//监测点1 TestLeak(); _CrtMemCheckpoint(&s2);//监测点2 if (_CrtMemDifference(&s3, &s1, &s2))//判断检监测点1和监测点2是否不同 { _CrtMemDumpStatistics(&s3);//打印泄漏内存 } _CrtDumpMemoryLeaks();//打印所有内存泄漏信息 system("pause"); return 0; }
_CrtMemDumpStatistics(&s3);输出信息如下,说明TestLeak()函数申请了有100字节的内存,尚没有释放;
0 bytes in 0 Free Blocks. 100 bytes in 1 Normal Blocks. 0 bytes in 0 CRT Blocks. 0 bytes in 0 Ignore Blocks. 0 bytes in 0 Client Blocks. Largest number used: 100 bytes. Total allocations: 100 bytes.
_CrtDumpMemoryLeaks();输出信息如下:
可以看到有100字节内存泄漏,位置为0x00000000000DC480。即TestLeak()函数中申请内存的位置;
Detected memory leaks!
Dumping objects ->
{75} normal block at 0x00000000000DC480, 100 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
Dumping objects ->
{75} normal block at 0x00000000000DC480, 100 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.