最近VCを利用してCPPプログラムの作業をやってます。ソース中メモリのコントロールところが多いですから、メモリリークをよく発生しました。毎回ソースコードを読んでnew-deleteをチェックすると時間をかかるのに効率が悪いです。_CrtSetBreakAllocを利用してチェックしてみました、使いやすい関数です。
_CrtSetBreakAlloc を使用すると、アプリケーションは、特定のメモリ割り当て位置にブレークポイントを設定し、要求元までトレースすることによって、メモリリークを検出できます。使用されるオブジェクト割り当て順序番号は、ヒープへの割り当て時にメモリ ブロックに割り当てられたシーケンシャル番号です。_DEBUG が未定義の場合、_CrtSetBreakAlloc の呼び出しはプリプロセスで削除されます。
オブジェクト割り当て順序番号は、Crtdbg.h で定義されている _CrtMemBlockHeader 構造体の lRequest フィールドに格納されます。デバッグ ダンプ関数のいずれかが出力するメモリ ブロック情報のレポートでは、中かっこで囲まれて {36} のように表示されます。
次は使用例です。
- // crt_setbrkal.c
- // compile with: -D_DEBUG /MTd -Od -Zi -W3 /c /link -verbose:lib -debug
- /*
- * In this program, a call is made to the _CrtSetBreakAlloc routine
- * to verify that the debugger halts program execution when it reaches
- * a specified allocation number.
- */
- #include <malloc.h>
- #include <crtdbg.h>
- int main( )
- {
- long allocReqNum;
- char *my_pointer;
- /*
- * Allocate "my_pointer" for the first
- * time and ensure that it gets allocated correctly
- */
- my_pointer = malloc(10);
- _CrtIsMemoryBlock(my_pointer, 10, &allocReqNum, NULL, NULL);
- /*
- * Set a breakpoint on the allocation request
- * number for "my_pointer"
- */
- _CrtSetBreakAlloc(allocReqNum+2);
- _crtBreakAlloc = allocReqNum+2;
- /*
- * Alternate freeing and reallocating "my_pointer"
- * to verify that the debugger halts program execution
- * when it reaches the allocation request
- */
- free(my_pointer);
- my_pointer = malloc(10);
- free(my_pointer);
- my_pointer = malloc(10);
- free(my_pointer);
- }
_CrtSetBreakAllocについてもっと詳しい情報と関連関数の説明は次のURLをクリックして参考してください。
http://msdn.microsoft.com/ja-jp/library/4wth1ha5(VS.80).aspx
メインコンテンツEND ■
Posted on Wednesday, 14th January 2009 by admin
Tags: CPP, CRT, _CrtSetBreakAlloc, _DEBUG
Posted in C/C++ | Comments (0) | 9,870 views
