Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

BSTR.CAST.CPP

Incorrect C++-style type cast to BSTR

The BSTR.CAST.C checker finds C++-style expressions that have been explicitly cast to a BSTR expression.

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.

Casting pointers that do not satisfy the BSTR specification to the BSTR type may cause problems with memory usage.

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

1  void bstr_cast_cpp() {
2    wchar_t *foo = L"abc";
3    BSTR bar = reinterpret_cast<BSTR>(foo);
4  }

Klocwork flags line 3, in which a non-BSTR variable, foo, is cast to a BSTR pointer.

Fixed code example

1  void bstr_cast_cpp() {
2    BSTR foo = SysAllocString(L"abc");
3    BSTR bar = reinterpret_cast<BSTR>(foo);
4  }

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