Microsoft KB Archive/194756

{|
 * width="100%"|

PRB: Cannot Use SysAllocStr to Create BSTRs; L"String"

 * }

Q194756

-

The information in this article applies to:


 * Microsoft Win32 Software Development Kit (SDK)

-

SYMPTOMS
A value of type L"String" passed as a BSTR value does not function correctly.

CAUSE
BSTR values are Unicode strings with a length prefix where the length is the number of bytes, excluding the terminating wide NULL. For example, the word "Hello" represented as a BSTR is the following:

"UINT(10) followed by UNICODE(Hello) - '\x0A\0\0\0H\0e\0l\0l\0o\0\0\0'" If you use a plain L"String" value instead of a proper BSTR value, the BSTR length function SysStringLen treats the value preceding the text (typically random values from the stack) as the byte count and uses half that value as the length.

RESOLUTION
Use the SysAllocString function to get a proper BSTR value. The allocated string must be released later by calling SysFreeString. Please note that you should not add the length prefix because the format of the BSTR is subject to change. Following is some sample code that illustrates this solution:

  BSTR pTempStr = SysAllocString(L"Test"); [insert code to use pTempStr here as needed] SysFreeString(pTempStr);