Welcome to MSDN Blogs Sign in | Join | Help
Careful with & operator on CComBSTR variables.

Be careful when using the & operator on a CComBSTR variable.  If this variable is not empty, using the & operator on it to point it to a new BSTR will lead to a memory leak.

For instance,

if you have a variable bsz1

declared and initialized as:

CComBSTR bsz1("HiWorld"); 

the member BSTR is allocated by issuing a call to SysAllocString.  If you use somewhere after that  in your code (&bsz1), you will cause a memory leak.

 

You can call  bsz1.empty() before you use &bsz1 to prevent from the memory leak.

 

Cheers.

Elyasse

Posted: Thursday, October 28, 2004 10:36 PM by elyasse
Filed under:

Comments

Pavel Lebedinsky said:

What's really strange is that unlike CComPtr, CComBSTR doesn't even assert that the pointer is NULL in its operator&.

I heard that this might be fixed in Whidbey, but in the meantime we manually added ATLASSERT(m_bstr == NULL) to our ATL sources. This single change has allowed us to find somewhere around 10-15 BSTR leaks, and generated only a few false positives.
# October 29, 2004 12:33 AM

G said:

Im confused. Can you explain this a little more? Simply taking the address of a CComBSTR causes a memory leak? I dont get it.
# October 29, 2004 10:11 AM

Pavel Lebedinsky said:

Taking the address does not cause the leak. Overwritng the pointer with something else does:

CComPtr<IXMLNode> spNode1, spNode2;

CComBSTR bstr;
spNode1->get_text (&bstr);
spNode2->get_text (&bstr);

The second get_text() call leaks the BSTR allocated by the first one.
# October 29, 2004 9:32 PM
Anonymous comments are disabled
Page view tracker