LoginSignup
1
0

More than 1 year has passed since last update.

crtdbg.h を使ってメモリリークを探しやすくする

Posted at

メモリリークはがあるのよねー…というのを見かけたので。

スマートポインタの利用も検討するといいと思うよ!というところもありますが今あるコードの問題が解決するわけじゃないですからね。

ってことで、お手軽手段を軽く紹介。

まずはVC++では同じみプリコンパイルヘッダーに以下のコードを入れておきます。
インクルードするヘッダーによっては順番の問題があることもあるので注意しましょう…<
<どうやって!

//プリコンパイルヘッダー
#include <crtdbg.h>
#include <memory.h>

#ifdef _DEBUG
# define DEBUG_NEW new(_CLIENT_BLOCK,__FILE__,__LINE__)
#endif

次はメイン関数と実際のメモリ確保部分。

// ソース
#include "pch.h"
#include "app.h"

#ifdef _DEBUG
# define new DEBUG_NEW
#endif

void MainRoutine();
int main()
{
  _CrtSetDbgFlag( _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG)| _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

  MainRoutine();

  return 0;
}
void MainRoutine()
{
  lstrcpy( new wchar_t[32], L"First Leak" );
}

デバッグ実行するとプログラム終了時にアウトプット画面に以下のような感じでリークメモリをダンプしてくれます。

とあるサンプルプログラムでの実行例です。
lstrcpy の行をそのままWinMainの最初に配置して試した例です。

Dumping objects ->
sample.cpp(41) : {221} client block at 0x0000027092637A90, subtype 0, 64 bytes long.
 Data: <F i r s t   L e > 46 00 69 00 72 00 73 00 74 00 20 00 4C 00 65 00 
Object dump complete.

もっと詳しく!という場合はリファレンスを見てくださいね。
CRT デバッグ ヒープ

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0