What are the common causes of COM memory leaks?

What are the most common causes of COM memory leaks?

I read that passing the address of the initialized CComBSTR function as the [out] parameter causes a leak. I am looking to list other common programming errors like this.

+4
source share
3 answers

Cannot use RAII wrapper types for COM objects. In particular, CComPtr<> , CComBSTR and CComVARIANT<> not used. These objects help prevent leaks by eliminating the responsibility for releasing the primary resource from the developer. The wrapper object enforces the destructor resources in it.

Another cause of leaks or random errors that I saw is the result of an implicit conversion from CComPtr<T> to T* . This is useful for passing wrapped objects as arguments. But this can cause problems because it allows an implicit conversion between the RAII object and the raw pointer. for instance

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

Calling SomeCall will most likely not work in this scenario, because the pFoo object is already dead. What for? The value was returned using ref count 1 from GetAFoo assigned by pFoo, and then decreased to 0 and removed because the temporary value fell out of scope.

+7
source

Forget calling Release () when you need to. Use CComPtr <>, CComVARIANT <>, and CComBSTR to help you.

+4
source

There are two main reasons: the use of RAII (smart pointers) and the improper use of RAII.

If you use raw pointers - IInterface * or BSTR, you risk forgetting to call IInterface :: Release () or SysFreeString (), and this will cause a leak. If you use smart pointers incorrectly, you also risk memory leaks. One way to do this is the one you mentioned - passing the initialized CComBSTR :: operator & () as the [out] parameter. There are other ways, such as passing CComPtr :: operator & () or CCOmQIPtr :: operator & () an initialized smart pointer as the [out] parameter with ATLASSERT disabled. Or create any graph-like structure with a loop and completely free it so that the object in the loop holds smart pointers to each other and does not let go.

+2
source

All Articles