プログラミングTips(Win32編)

メモリリークを検出する

ATLプログラムのメモリリークを検出する手順です。
  1. プログラム開始時にメモリ状態を取得します。
    _CrtMemState mOldMemState;
    _CrtMemCheckpoint(&mOldMemState);
    
  2. プログラムの終了時に再度メモリ状態を取得します。
    _CrtMemState mCurMemState;
    _CrtMemCheckpoint(&mCurMemState);
    
  3. メモリ状態を比較し、異なっていればダンプします。
    _CrtMemState mDiffMemState;
    if ( _CrtMemDifference(&mDiffMemState, &mOldMemState, &mCurMemState) ) {
    	ATLTRACE( "***Memory leaked!\n" );
    	ATLTRACE( "***DumpAllObjectsSince\n" );
    	_CrtMemDumpAllObjectsSince(&mDiffMemState);
    	ATLTRACE( "***DumpStatistics\n" );
    	_CrtMemDumpStatistics(&mDiffMemState);
    }
    
  4. サンプル出力結果
    ***Memory leaked!
    ***DumpAllObjectsSince
    Dumping objects ->
    {54} normal block at 0x00CC1C50, 12 bytes long.
     Data: <            > CD CD CD CD CD CD CD CD CD CD CD CD 
    {53} normal block at 0x00CC1C90, 4 bytes long.
     Data:  4C FE 12 00 
    {52} normal block at 0x00CC1CC0, 4 bytes long.
     Data:  48 FE 12 00 
    {51} normal block at 0x00CC1CF0, 8 bytes long.
     Data: <        > E6 00 03 00 08 00 CC CC 
    {46} normal block at 0x00CC1D30, 8 bytes long.
     Data: <        > 00 00 00 00 00 00 00 00 
    {45} normal block at 0x00CC1D70, 4 bytes long.
     Data: <    > 88 FE 12 00 
    {44} normal block at 0x00CC0030, 4 bytes long.
     Data: <    > B0 08 00 00 
    {43} normal block at 0x00CC1DA0, 12 bytes long.
     Data: <0   p       > 30 00 CC 00 70 1D CC 00 01 00 00 00 
    Object dump complete.
    ***DumpStatistics
    0 bytes in 0 Free Blocks.
    12 bytes in 1 Normal Blocks.
    0 bytes in 0 CRT Blocks.
    0 bytes in 0 Ignore Blocks.
    0 bytes in 0 Client Blocks.
    Largest number used: 0 bytes.
    Total allocations: 12 bytes.