« 縮小専用。 | Main | Flickr »

09 February 2006

MFCでメモリリークを調べる

MFCネタ。Windowsアプリケーションを作成していると、ときどきメモリリークが発生することがある。さてどのコードか分からない。そんなときにおすすめなのがCMemoryStateクラス

例えばこんな感じ。


CMemoryState hereMem;
hereMem.Checkpoint();

// メモリリークが発生していそうななんかの処理

CMemoryState thereMem;
thereMem.Checkpoint();

CMemoryState checker;
if (checker.Difference(hereMem, thereMem))
{
// hereとthereで相違があったみたい。
// アウトプットウインドウへ出力してみる。
checker.DumpStatistics();
}

という具合。

ちょっとおっちょこちょいな例としては、
関数の中のメモリリークを探してみようとして、
関数ブロックの先頭と終端にCheckpoint()を設定しちゃった場合。


void CSample::Function()
{
CMemoryState oldMem;
oldMem.Checkpoint();

char szBuf[BUFSIZ];

CMemoryState newMem;
newMem.Checkpoint();

CMemoryState checker;
if (checker.Difference(oldMem, newMem)) {
}
}

ローカル変数は関数を抜けてから解放されます。つまり関数にいる間はメモリが確保された状態になります。なので一瞬リークしたように感じます。
そんなときは、


CSample cSample;

CMemoryState oldMem;
oldMem.Checkpoint();

cSample.Function();

CMemoryState newMem;
newMem.Checkpoint();

CMemoryState checker;
if (checker.Difference(oldMem, newMem)) {
}

このように呼び出し元で関数をくくった方が良いです。その後で関数の中に入るなりして、範囲を狭めていくと良いのではないでしょうかね。慌てず騒がず粛々と進めましょう。

TrackBack

TrackBack URL for this entry:
http://bb.lekumo.jp/t/trackback/517129/31023583

Listed below are links to weblogs that reference MFCでメモリリークを調べる:

Comments

taylor armstrong divorce aide divorce femme

notaire pour divorce divorce causes

Tirage de carte de marseille gratuit oracle oui ou non gratuit

You actually make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand. It seems too complicated and extremely broad for me. I'm looking forward for your next post, I will try to get the hang of it!

wonderful issues altogether, you just gained a emblem new reader. What could you recommend about your post that you made a few days ago? Any certain?

This text is priceless. How can I find out more?

Thanks for the good writeup. It in fact was once a leisure account it. Glance advanced to far added agreeable from you! However, how could we be in contact?

Woah! I'm really enjoying the template/theme of this blog. It's simple, yet effective. A lot of times it's tough to get that "perfect balance" between superb usability and visual appeal. I must say that you've done a awesome job with this. Additionally, the blog loads super fast for me on Opera. Excellent Blog!

Post a comment

Access Ranking

Powered by Six Apart
Sponsored links