Memory leak for CComBSTR

atl, bstr, com, com-interop, memory-leaks

Solution

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.

Problem

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?

Original source