BUG: CComVariant::operator=(BSTR) Does Not Copy Embedded NULL Characters (251023)



The information in this article applies to:

  • The Microsoft Active Template Library (ATL) 2.0
  • The Microsoft Active Template Library (ATL) 2.1
  • The Microsoft Active Template Library (ATL) 3.0

This article was previously published under Q251023

SYMPTOMS

When you assign BSTR to a CComVariant instance using CComVariant::operator=(BSTR), any characters after an embedded NULL character in BSTR are not copied.

CAUSE

This is due to the implementation of CComVariant::operator=(BSTR) not accounting for NULL characters inside BSTR being copied.

RESOLUTION

Instead of using CComVariant::operator=(BSTR) to copy BSTR inside of CComVariant, use the CComVariant::Copy() function and place BSTR inside of VARIANT. The following code snippet could be used to replace CComVariant::operator=(BSTR) if you need to make sure embedded NULL characters and characters after embedded NULL characters are copied.
void Function(BSTR bstrValue)
{
  VARIANT v;
  v.vt = VT_BSTR;
  v.bstrVal = bstrValue;

  CComVariant a;
  a.Copy(&v); //Use this instead of the next line.
  //a = bstrValue; //This would not copy embedded NULLs or chars after NULL.

  //Use variant now to do whatever you need.
}
				

STATUS

Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article.

Modification Type:MajorLast Reviewed:10/2/2003
Keywords:kbBug kbfix KB251023