內存泄露:常見的new創建的對象沒有delete釋放掉,導致內存的泄露,以後這部分空間將無法再被使用,就會產生Heap Leak。
兩種方法檢查代碼中存在的內存泄漏:使用自帶的庫和使用工具。
一 使用自帶的庫crtdbg.h
不用安裝工具,但需要不斷的手動修改中斷位置。
#include <crtdbg.h>
int main()
{
//_CrtSetBreakAlloc(77); //在申請指定內存的位置中斷
int *p = new int[10];
_CrtDumpMemoryLeaks();//檢查內存泄漏
return 0;
}
在main函數最後加_CrtDumpMemoryLeaks(); 然後debug調試程序,會輸出泄露的內存位置。
Detected memory leaks!
Dumping objects ->
{77} normal block at 0x008F5500, 40 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
{77}是內存泄露定位值,有40字節泄露。
在main函數開始加_CrtSetBreakAlloc(77); 然後調試,會在申請指定內存(77)的位置中斷。
二、安裝工具
下載安裝vld-2.5-setup.exe 百度搜索或雲盤下載https://pan.baidu.com/s/1FHK7jk87EIzFF-0ipaeCSA
直接默認安裝即可。會提示關閉VS,然後自動配置VS。
此工具好像不支持2017(會提示內存泄漏,但不定位行號),需要修改。
用以下VS2017的兩個dll替換VLD的。
%programfiles(x86)%\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TestWindow\Extensions\Cpp\dbghelp.dll 到 %programfiles(x86)%\Visual_Leak_Detector\bin\Win32
%programfiles(x86)%\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TestWindow\Extensions\Cpp\x64\dbghelp.dll 到 %programfiles(x86)%\Visual_Leak_Detector\bin\Win64
#include "vld.h" 然後調試就會定位行號了。