笔记:之前研究过如何定位内存泄漏,太长时间不用又忘记了,今天把它记下来!
学而时习之
内存泄漏的原因
C++和其他高级语言不同,需要自行管理内存,项目大\调用多,容易内存泄漏.内存申请释放使用malloc/free和new delete两种方式。
有经验的程序员会对程序中申请内存的地方进行排查,例如malloc或者new关键字的地方进行跟踪,一种情况是我们按照程序逻辑进行了申请和释放,要提防程序在发生异常时没有如我们所期望的那样进行内存释放,此时也应当防止内存泄漏。
排查方法
windows CRT调试(Find memory leaks with the CRT library)
这是最方便的方法。
官方有详细使用描述:官网链接:Find memory leaks with the CRT Library - Visual Studio (Windows) | Microsoft Docs
使用案例:
// debug_new.cpp
// compile by using: cl /EHsc /W4 /D_DEBUG /MDd debug_new.cpp
#define _CRTDBG_MAP_ALLOC
#include <cstdlib>
#include <crtdbg.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
#