开发者

External memory management and COM

Having trouble with memory management of a third party library. I have the source but it's very complex (COM stuff), full of macros and those annoying Microsoft annotations, etc, and interacts with another library the source of which I don't have to boot. Now some quick debug runtimes have shown that it's leaking memory and in a pretty big way. I make extensive use of self-releasing pointers like unique_ptr 开发者_StackOverflow社区and know that I released everything that I created. Is it my only option to try and clean up (and understand) the source?

In addition, is it safe to allocate COM objects with operator new, or do they have to go in the COM heap?


COM is quite agnostic about how you allocate your own COM objects. They get created by the class factory and your IUnknown::AddRef and Release methods keep the reference count. Using operator new in the class factory and delete this in Release is fine.

You do have to be careful about any pointers you return in your interface methods. Typical Automation objects like BSTR and SAFEARRAY do indeed need to be allocated in the COM heap so that the client code can release them. Pretty hard to mess that up, the API does the work.

The client code can be responsible for the leak, fumbling the reference count is a pretty standard COM bug. Usually easy to diagnose when you have access to the AddRef/Release implementations. Debugging this in Vista or Win7 is also strongly recommended, they have a much better heap manager that doesn't silently ignore attempts to free memory from the wrong heap.

If you're pretty sure it is the COM server that leaks then isolate the problem with the <crtdbg.h> header and unit tests to exercise the interface methods.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜