定位 new 分配的内存泄漏位置:
1.使用宏定义:输出内存泄漏的文件以及行数
#ifdef _DEBUG
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
// Replace _NORMAL_BLOCK with _CLIENT_BLOCK if you want the
// allocations to be of _CLIENT_BLOCK type
#else
#define DBG_NEW new
#endif
2.在程序中包含一下库和#define
To enable all the debug heap functions, include the following statements in your C++ program, in the following order:
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
3.在程序起始点写:
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
这会在每个函数的结束位置自动调用:_CrtDumpMemoryLeaks();
并生成内存泄漏报告
example:
#pragma once
//#include "pch.h"
#include "BlackPearl/Application.h"
#include "BlackPearl/Log.h"
#ifdef _DEBUG
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
// Replace _NORMAL_BLOCK with _CLIENT_BLOCK if you want the
// allocations to be of _CLIENT_BLOCK type
#else
#define DBG_NEW new
#endif
#define _CRTDBG_MAP_ALLOC
#include <cstdlib>
#include <crtdbg.h>
#ifdef GE_PLATFORM_WINDOWS
extern BlackPearl::Application* BlackPearl::CreateApplication();
int main() {
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
BlackPearl::Log::Init();
GE_CORE_WARN("Initialized Log!");
BlackPearl::Application* app = BlackPearl::CreateApplication();
app->Run();
delete app;
//_CrtDumpMemoryLeaks();
}
#endif
4.在vs输出窗口可以看到内存泄漏的位置: