最近VCを利用してCPPプログラムの作業をやってます。ソース中メモリのコントロールところが多いですから、メモリリークをよく発生しました。毎回ソースコードを読んでnew-deleteをチェックすると時間をかかるのに効率が悪いです。_CrtSetBreakAllocを利用してチェックしてみました、使いやすい関数です。

_CrtSetBreakAlloc を使用すると、アプリケーションは、特定のメモリ割り当て位置にブレークポイントを設定し、要求元までトレースすることによって、メモリリークを検出できます。使用されるオブジェクト割り当て順序番号は、ヒープへの割り当て時にメモリ ブロックに割り当てられたシーケンシャル番号です。_DEBUG が未定義の場合、_CrtSetBreakAlloc の呼び出しはプリプロセスで削除されます。

オブジェクト割り当て順序番号は、Crtdbg.h で定義されている _CrtMemBlockHeader 構造体の lRequest フィールドに格納されます。デバッグ ダンプ関数のいずれかが出力するメモリ ブロック情報のレポートでは、中かっこで囲まれて {36} のように表示されます。

次は使用例です。

  1. // crt_setbrkal.c
  2. // compile with: -D_DEBUG /MTd -Od -Zi -W3 /c /link -verbose:lib -debug
  3.  
  4. /*
  5. * In this program, a call is made to the _CrtSetBreakAlloc routine
  6. * to verify that the debugger halts program execution when it reaches
  7. * a specified allocation number.
  8. */
  9.  
  10. #include <malloc.h>
  11. #include <crtdbg.h>
  12.  
  13. int main( )
  14. {
  15.         long allocReqNum;
  16.         char *my_pointer;
  17.  
  18.         /*
  19.          * Allocate "my_pointer" for the first
  20.          * time and ensure that it gets allocated correctly
  21.          */
  22.         my_pointer = malloc(10);
  23.         _CrtIsMemoryBlock(my_pointer, 10, &allocReqNum, NULL, NULL);
  24.  
  25.         /*
  26.          * Set a breakpoint on the allocation request
  27.          * number for "my_pointer"
  28.          */
  29.         _CrtSetBreakAlloc(allocReqNum+2);
  30.         _crtBreakAlloc = allocReqNum+2;
  31.  
  32.         /*
  33.          * Alternate freeing and reallocating "my_pointer"
  34.          * to verify that the debugger halts program execution
  35.          * when it reaches the allocation request
  36.          */
  37.         free(my_pointer);
  38.         my_pointer = malloc(10);
  39.         free(my_pointer);
  40.         my_pointer = malloc(10);
  41.         free(my_pointer);
  42. }

_CrtSetBreakAllocについてもっと詳しい情報と関連関数の説明は次のURLをクリックして参考してください。

http://msdn.microsoft.com/ja-jp/library/4wth1ha5(VS.80).aspx
メインコンテンツEND ■
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Posted on Wednesday, 14th January 2009 by admin

Tags: , , ,
Posted in C/C++ | Comments (0) | 9,870 views

Leave a Reply