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:\users\zly\documents\visual studio 2013\projects\testopencv\testopencv\testopencv.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.
參考文章