BSTR.IA.INIT

BSTR variable is initialized with a non-BSTR value

The BSTR.IA.INIT checker finds code in which BSTR variable is initialized with a non-BSTR value. BSTR variables can be initialized only with null constants or values of type BSTR.

Vulnerability and risk

Because the two styles are constructed differently, converting COM-style BSTR strings to and from C-style strings needs care. In some cases, conversions between the two compile well, but still produce unexpected results.

Mitigation and prevention

Unlike C-style strings, BSTR strings have a 4-byte length prefix that contains the number of bytes in the following data string. BSTR strings can also contain embedded null characters, and aren't strongly typed. For these reasons, it's best not to use BSTR in new designs. For existing interfaces, it's important to make conversions and use the Sys*Alloc*, SysFree* and Sys*String* memory allocation functions carefully.

If a BSTR string is initialized with a wide character string that does not satisfy this rule (for example, a wide character string constant), problems with memory usage may occur.

Vulnerable code example

Copy
  void bstr_init() {
       BSTR foo = L"abc"; 
  }

Klocwork flags line 2, in which the BSTR variable is initialized with a non-BSTR value.

Fixed code example

Copy
  void bstr_init() {
       BSTR foo = SysAllocString(L"abc"); 
  }

In this fixed example, we assume that the variable foo was intended to be a BSTR, so it's defined as BSTR using the correct SysAllocString conversion function.

Related checkers