开发者

detecting memory leaks in C++ / windows

For debugging purposes, when I'm writing an app, the first thing I do is put the following into the stdafx.h:

// -- leak detection ----------------------------------------------------------
#ifdef _DEBUG   
// http://msdn.microsoft.com/en-us/library/e5ewb1h3(v=VS.80).aspx
#define _CRTDBG_MAP_ALLOC   
#include <stdlib.h>
#include <crtdbg.h>
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
#endif

Then I add the following to the beginning of the program's main() function:

#ifdef _DEBUG
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
//_CrtSetBreakAlloc( 670 );
#endif  

Redefining the new operator to give leak information is a useful tool. But what about CoTaskMemAlloc and CoTaskMemFree ? How can I detect leaks using these?

I'm writing software that uses COM and DirectShow and need to know how to trace leaks caused by using CoTask allocatio开发者_StackOverflow中文版ns.

thanks!


Get rid of manual memory management and you'll get rid of leaks. Embrace RAII, and never use a resource unless it's wrapped in a handler whose single purpose is to wrap that resource.

I don't think I had a memory leak (or a crash, FTM) in years. But then I have written delete less than half a dozen times in the last decade.


Visual Leak Detector - pretty easy to use and there'e no overhead for the app built in release.


There is also application verifier. It can track a whole bunch of other issues as well apart from leaks like places where you forget to free win32 objects such as handles etc ...

The MSDN link is: http://msdn.microsoft.com/en-us/library/ms220948(VS.80).aspx

Taken from a similar quesiton at Visual C++ - Memory Leak Detection


But what about CoTaskMemAlloc and CoTaskMemFree ? How can I detect leaks using these?

You cannot for the same reason that malloc/free doesn't help you to detect leaks. You need to wrap them suitably to help you with leak detection.

As other posters have said if you are worried about leaks, then start designing your application ground up with this requirement in mind. Use custom allocators where you can manage/track allocations/deallocations.

Did you happen to visit this question: Usage of CoTaskMemAlloc?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜