Re: ATL CComBSTR.Copy Fails in VC9, works in VC6
Chizl <Chizl@NoShitMail.com> wrote:
It's returning a access violation. This is the function that's
failing only in VC9, but works in VC6..
Purely by accident.
==============================================
STDMETHODIMP CLogging::GetGUID(BSTR* bstrGUID)
{
GUID guid;
CComBSTR bstr;
CoCreateGuid(&guid);
StringFromCLSID(guid, &bstr);
StringFromCLSID doesn't produce a BSTR - it doesn't allocate the memory
with SysStringAlloc, but with CoTaskMemAlloc. In particular, the string
doesn't have the length prefix, so SysStringLen would return random
garbage for such a string.
*bstrGUID= bstr.Copy();
return S_OK;
}
==============================================
This is the code I ended up with, but the caller has to deallocate
bstrGUID, which I'm not too fond of.
The caller had to deallocate bstrGUID in your original code, too. If it
didn't, it was leaking memory.
==============================================
STDMETHODIMP CLogging::GetGUID(BSTR* bstrGUID)
{
GUID guid;
CoCreateGuid(&guid);
StringFromCLSID(guid, bstrGUID);
This has the same problem - you are storing a pointer that's not a valid
BSTR in a BSTR variable. You've just shifted the consequences of that
problem on to your caller.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925