LoginSignup
1
2

More than 3 years have passed since last update.

Visual Studioメモ

Posted at

メモリリーク検出用デバッグコード

Visual C++を使用したソフトウェア開発において,メモリリークを発生させるコードは気を付けていても作り込まれてしまうもの。
これはC/C++の宿命のようなものであるが,メモリリークの要因は,メモリリーク検出用のデバッグコードを埋め込むことにより,容易に取り除くことができる。

(1) メモリリークが疑われるソースコードの先頭行に以下の宣言文を追加する。

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define new ::new(_NORMAL_BLOCK, __FILE__, __LINE__)

(2) メモリリークの候補をDUMPする。

OutputDebugString(_T("Dump memory leaks"));
_CrtDumpMemoryLeaks();

Visual C++からデバッグモードでプログラムを起動すると,上記#2のDUMP情報がVisual C++のコンソールに出力される。
出力される情報は下記のとおり。

  • メモリ割り当て番号 (中括弧に囲まれた数字)
  • ブロックの型 (Normal、Client または CRT)
  • 16 進数で表されるメモリの位置
  • バイト単位で表されるブロックのサイズ
  • 先頭の 16 バイトの内容 (16 進数)
c:\work\github\yaizucomlib\src\commonfunc\stkobject.cpp(716) : {3539} normal block at 0x00AB4CE8, 32 bytes long.
Data: <HM M > 48 4D AB 00 16 00 00 00 90 4D AB 00 00 00 00 00

OutputDebugStringおよび_CrtDumpMemoryLeaksのみでもDUMP情報は出力されるが,前述#defineおよび#includeを挿入することにより, ソースコードのファイル名とメモリ確保を行った行番号が出力される。

Visual Studioの検索・置換における正規表現

_T("xxx")をL"xxx"に置換する例。

検索: _T\("(.*)"\)
置換: L"$1"
1
2
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
2