📄 memstate.cpp
字号:
// memstate.cpp: Microsoft specific memory state functions, for finding memory leaks// Warning: this is raw research code -- expect it to be quite messy.#include <stdio.h>#include <stdlib.h>#include <string.h>#include <malloc.h>#include <crtdbg.h>#define CONF_fAbortOnMemLeak 0#if _DEBUGstatic _CrtMemState gMemStateMarked;#endif//-----------------------------------------------------------------------------// After calling this, on program termination we will get a report if there are// writes outside the borders of allocated blocks or if there are non-freed blocks.//// fDelayFree=TRUE delays freeing memory so illegal use of free memory is caught.// But with masm.exe, fDelayFree=TRUE causes us to run out of memory// (because we allocate and then free big blocks which aren't actually freed)// so the flag can't be used with masm.exevoid InitMallocDebug (bool fDelayFree){#if _DEBUG_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_WNDW);_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);int Flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);Flag |= (_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);if (fDelayFree) Flag |= _CRTDBG_DELAY_FREE_MEM_DF;_CrtSetDbgFlag(Flag);#endif}//-----------------------------------------------------------------------------void MarkMemState (void){#if _DEBUGInitMallocDebug(true);_CrtMemCheckpoint(&gMemStateMarked); // remember the current memory allocation status#endif}//-----------------------------------------------------------------------------bool fCheckMemState (char *sMsg){#if _DEBUGif (sMsg) printf("%s ", sMsg);printf("memory use: ");bool fLeak = false;_CrtMemState MemStateNow, MemStateDiff;_CrtMemCheckpoint(&MemStateNow); // get the current memory allocation statusif (_CrtMemDifference(&MemStateDiff, &gMemStateMarked, &MemStateNow)) // did it change? { for (int iUse = 0; iUse < _MAX_BLOCKS; iUse++) if (MemStateDiff.lCounts[iUse]) { fLeak = true; printf("%d:%ld ", iUse, MemStateDiff.lSizes[iUse]); } }fflush(stdout);if (!fLeak) { printf("0 "); }else { _CrtMemDumpAllObjectsSince(NULL);#if CONF_fAbortOnMemLeak *(int *)100 = 0; // force an access violation#endif }printf("bytes\n");return fLeak;#endifreturn false;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -