BSTR.FUNC.ALLOC

Incorrect call to BSTR allocation function

The BSTR.FUNC.ALLOC checker finds calls to BSTR allocation functions SysAllocString and SysAllocStringLen when a value of type BSTR is specified as the argument for the function.

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.

Vulnerable code example

Copy
  void bstr_alloc() {
    BSTR foo = SysAllocString(L"abc"), bar;
    bar = SysAllocString(foo);  
  }

Klocwork flags line 3 of this example. SysAllocString treats its argument as a normal, null-terminated C-string, so any embedded null characters in a BSTR string can cause problems with this function. The shorter string resulting from SysAllocString with a BSTR variable can cause unexpected consequences.

Fixed code example

Copy
  void bstr_alloc() {
    BSTR foo = SysAllocString(L"abc"), bar;
    bar = foo; 
    SysFreeString(bar)   
  }

In the fixed example, SysAllocString is removed from line 3, and in addition, the correct SysFreeString function is used to release memory.