Elyasse Elyacoubi's Weblog

Elyasse El Yacoubi - MSFT

Careful with & operator on CComBSTR variables.

Careful with & operator on CComBSTR variables.

  • Comments 3

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

  • 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.
  • Im confused. Can you explain this a little more? Simply taking the address of a CComBSTR causes a memory leak? I dont get it.
  • 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.
Page 1 of 1 (3 items)