Visual C++ でメモリリークを検出する方法。

main 関数の出口で _CrtDumpMemoryLeaks 関数を呼ぶことによって、メモリリークを検出できる。ただ、下のようにあらかじめ_CrtSetDbgFlag で設定しておくことにより、プログラムがどのような終了の仕方をしても_CrtDumpMemoryLeaks 関数を呼んでくれるので、そのほうがよさそう。
// LeakTest1.cpp : コンソール アプリケーションのエントリ ポイントを定義します。
//

#include "stdafx.h"

#if WIN32
#include 
#define _CRTDBG_MAP_ALLOC
#ifdef _DEBUG
#define new  ::new(_NORMAL_BLOCK, __FILE__, __LINE__)
#endif
#endif

int _tmain(int argc, _TCHAR* argv[])
{
#if WIN32
	// デバッグウィンドウに出力
	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG);
	_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);
	_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
	//_CrtSetBreakAlloc(146);	// ブレークさせたいとき用
#endif

	// わざとメモリーリークさせる
	char* p1 = new char[5];
	int* p2 = new int[3];

	return 0;
}

実行結果は以下のとおり。上のサンプルだと出力先は出力ウィンドウとなっているが、ファイルやウィンドウに出力させることもできる。
Detected memory leaks!
Dumping objects ->
c:\work\leaktest1\leaktest1.cpp(27) : {147} normal block at 0x0072EC70, 12 bytes long.
 Data: <            > CD CD CD CD CD CD CD CD CD CD CD CD 
c:\work\leaktest1\leaktest1.cpp(26) : {146} normal block at 0x0072EC28, 5 bytes long.
 Data: <     > CD CD CD CD CD 
Object dump complete.

以上。