Memory leak for CComBSTR
Asked Answered
R

2

7

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?

Redtop answered 16/11, 2009 at 23:12 Comment(0)
G
11

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.

Ganglion answered 16/11, 2009 at 23:53 Comment(2)
So if we have just the first two lines CComBSTR str; pFoo->get_Bar(&str); then it wont cause a leak and there is no need to Empty it right.Redtop
I once proposed a leak warning in CComBSTR, but I'm not sure if it's still there (don't have Visual Studio on this machine). There should be an assertion that fires if you try to use operator& on an initialized CComBSTR. It may be that you need to define some symbol to enable it -- see CComBSTR's source.Chaumont
M
4

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.

Marilumarilyn answered 16/11, 2009 at 23:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.