Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the frequently-encountered causes for COM memory leaks?

What are the most frequently encountered causes for COM memory leaks?

I have read that passing the address of an initialized CComBSTR to a function as an [out] parameter causes a leak. I'm looking to enumerate other common programming mistakes like this.

like image 799
Julian Avatar asked Dec 13 '22 01:12

Julian


2 Answers

Failing to use RAII wrapper types for COM objects. In particular not using CComPtr<>, CComBSTR and CComVARIANT<>. These objects help prevent leaks by removing the responsibility of releasing the underlying resource from the developer. The wrapping object enforces the release of resources in it's destructor.

Another cause of leaks or accidental frees I've seen is a result of the implicit conversion from CComPtr<T> to T*. This is useful for passing wrapped objects as arguments. But it can cause problems because it allows for the implicit conversion between a RAII object and a raw pointer. For example

CComPtr<IFoo> GetAFoo();  // Imagine if this creates the object
...
IFoo* pFoo = GetAFoo();   
pFoo->SomeCall();  

The call to SomeCall will likely fail in this scenario because the object pFoo is dead at this point. Why? The value was returned with a ref count of 1 from GetAFoo, assigned to pFoo and then decremented to 0 and deleted because the temporary value fell out of scope.

like image 138
JaredPar Avatar answered Jan 25 '23 23:01

JaredPar


Forgetting to call Release() when you should. Use CComPtr<>, CComVARIANT<> and CComBSTR to help you.

like image 21
i_am_jorf Avatar answered Jan 26 '23 00:01

i_am_jorf