c++内存泄露检测

// 以下代码在vs2013上面测试
#include <stdlib.h> #include <crtdbg.h> // 在入口函数中包含 _CrtDumpMemoryLeaks(); // 即可检测到内存泄露 typedef void* HObjectDetect; typedef struct tagOBJECTBBOX { float x1; float y1; float x2; float y2; float sc; }ObjectBBox, *HObjectBBox; HObjectDetect object_detect_init() { return new int; } void object_detect_clear(HObjectDetect hobjdetect) { delete hobjdetect; } void object_detection(HObjectBBox* phobjbbox) { HObjectBBox hobjbbox = new ObjectBBox[2]; hobjbbox[0].x1 = 1; hobjbbox[1].x2 = 2; *phobjbbox = hobjbbox; } void object_detection_delete_objbbox(HObjectBBox hobjbbox) { delete hobjbbox; hobjbbox = nullptr; } int _tmain(int argc, _TCHAR* argv[]) { HObjectDetect hobjdetect = object_detect_init(); HObjectBBox hobjbbox = nullptr; object_detection(&hobjbbox); object_detection_delete_objbbox(hobjbbox); object_detect_clear(hobjdetect); _CrtDumpMemoryLeaks();return 0; }


注释掉://object_detect_clear(hobjdetect);

Detected memory leaks!
Dumping objects ->
{116} normal block at 0x005BC768, 4 bytes long.
 Data: <    > CD CD CD CD
Object dump complete.

注释掉://object_detection_delete_objbbox(hobjbbox);

Detected memory leaks!
Dumping objects ->
{117} normal block at 0x005FC7A8, 40 bytes long.
 Data: <   ?            > 00 00 80 3F CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.

如果重新定义new,可以输出具体位置

#ifdef _DEBUG 
#define new   new(_NORMAL_BLOCK, __FILE__, __LINE__) 
#endif

Detected memory leaks!
Dumping objects ->
c:userszlydocumentsvisual studio 2013projects estopencv estopencv estopencv.cpp(38) : {117} normal block at 0x0067C7A8, 40 bytes long.
 Data: <   ?            > 00 00 80 3F CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.

参考文章

http://blog.csdn.net/windows_nt/article/details/8652191

原文地址:https://www.cnblogs.com/linyuanzhou/p/6121872.html