Memory Leak for CComBSTR

I read that the following code is causing a memory leak. But I did not understand why.

CComBSTR str; pFoo->get_Bar(&str); pFoo->get_Baf(&str); 

How does this cause a leak when we donโ€™t emit anything?

+7
memory-leaks com com-interop atl bstr
source share
2 answers

It get_Bar() because get_Bar() and get_Baf() do not know that you are using CComBSTR.

When you take the CComBSTR address, what you are actually passing to the base object is a pointer to the CCOMBSTR BSTR member element.

Violation of the sequence:

 CComBSTR str; 

This initializes the internal BSTR to NULL.

 pFoo->get_Bar(&str); 

get_Bar() sees BSTR * and populates it with actual data. Like this:

 HRESULT get_Bar(BSTR* arg) { *arg = SysAllocString(L"My String"); } 

Now the internal BSTR str is the real BSTR. When CComBSTR goes out of scope, it removes the str member.

Now, if you call get_Baf() on & str, the problem is that CComBSTR does not know that you are changing the string. Therefore, you call get_Baf() as follows:

 HRESULT get_Baf(BSTR* arg) { *arg = SysAllocString(L"My String"); } 

Now get_Baf() overwrites the original str value of the internal BSTR without freeing all the data allocated by get_Bar() .

Ta da is a memory leak.

+11
source share

This Microsoft page is probably where you read it:

http://msdn.microsoft.com/en-us/library/bdyd6xz6.aspx

Memory leak problems

Passing the address of the initialized CComBSTR function as the [out] parameter causes a memory leak.

The CComBSTR object allocates internal memory. Obviously, there are times when he does not release him.

+4
source share

All Articles