Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak for CComBSTR

I have read that the following code causes memory leak. But did not understand why.

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

How does it cause a leak when we are not allocating anything?

like image 395
Julian Avatar asked Nov 16 '09 23:11

Julian


2 Answers

It leaks because get_Bar() and get_Baf() don't know that you're using a CComBSTR.

When you take the address of a CComBSTR what you're actually passing to the underlying object is a pointer to the CComBSTR's BSTR member.

Breaking down the sequence:

CComBSTR str;

This initializes the internal BSTR to NULL.

pFoo->get_Bar(&str);

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

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

Now the internal BSTR of str is a real BSTR. When CComBSTR goes out of scope it will delete the str member.

Now if you call get_Baf() on &str the problem is that the CComBSTR doesn't know that you are changing the string. So you call get_Baf() like this:

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

Now get_Baf() has overwritten the original value of str's internal BSTR without anyone freeing the data that was allocated by get_Bar().

Ta da - Memory leak.

like image 135
Aaron Avatar answered Sep 21 '22 14:09

Aaron


This Microsoft page is probably the where you read about it:

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

Memory Leak Issues

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

The CComBSTR object is allocating memory internally. Evidently there are cases where it doesn't release it.

like image 4
Mark Ransom Avatar answered Sep 20 '22 14:09

Mark Ransom