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

PORTING.CMPSPEC.TYPE.BOOL

Assignment to a bool type larger than 1 byte

The PORTING checkers identify code that might rely on specific implementation details in different compilers. The PORTING.CMPSPEC.TYPE.BOOL checker detects situations in which an assignment to a Boolean type is larger than 1 byte.

Vulnerability and risk

The Boolean data type (bool) is intended to hold the values 1 (true) or 0 (false), but it can be forced to rely on ANSI typing rules, which are very flexible and allow Boolean types to be treated as integer types. This can cause problems when porting between compilers with differing levels of flexibility, so this checker enforces a 1-byte allocation maximum for any Boolean data type.

Mitigation and prevention

Don't interchange Boolean data with other integer-type data. The C++ standard defines Boolean keywords "true" and "false" to represent integer values 1 and 0, respectively. In addition, many compilers define TRUE and FALSE macros or suitable placeholders, or you can define your own values.

Vulnerable code example


1   void foo()
2   {
3     bool b;

4       b = 0x100;
5   }

Some compilers may choose to treat this as if the Boolean variable had been assigned a true value and store a simple '1', while issuing a warning to the effect that truncation from integer to bool type has taken place. Others may fall back on simple ANSI typing and store the 0x100 value specified. This lack of interchangeability will cause porting problems in data transmission or persistent storage.

Fixed code example


1   #define MY_TRUE  0x01
2   #define MY_FALSE 0x00

3   void foo()
4   {
5     bool b;

6       b = MY_TRUE;
7       b = 1;
8       b = true;
9   }

In the fixed example, the code defines its own values for the Boolean true and false, so the code can be ported without problems.