tags:

views:

26

answers:

1

I believe the following causes a memory access violation error as the false parameter (fcopy) causes the memory to be released for the CComBSTR:

CComBSTR myCComBSTR;
string strMyCComBSTR = string(_bstr_t(myCComBSTR, false));

However, I'm not quite sure why this is as the MSDN documentation says the following about fcopy:

If false, the bstr argument is attached to the new object without making a copy by calling SysAllocString.

My question is:

  1. Am I right in saying that this is a problem
  2. If so - why?

Thanks

+2  A: 

Yes, this is a problem - both myCComBSTR and the temporary will try to free the string since they both will think they own it.

You see, fcopy having value of false means "please don't duplicate the string body, just attach to the body I give you". When the first line completes you have myCComBSTR owning the string buffer and when the temporary object on the second line is created it also takes ownership of the same string buffer because of fcopy being false. Then the temporary is destroyed and frees the string buffer. Later myCComBSTR will be destroyed and will try to free the same string buffer again - you run into so-called double free which induces undefined behavior.

sharptooth
+1 Would this also be a problem if we used a BSTR instead of a CComBSTR? I assume not as BSTR is a raw ptr so would not release memory if it goes out of scope?
David Relihan
@David Relihan: Do you mean just cast to BSTR like this `(BSTR)something`? That would depend. In your case it would be simpler to just not change `fcopy` and let it be true.
sharptooth