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
b = 0x100;
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
#define MY_TRUE 0x01
#define MY_FALSE 0x00
b = MY_TRUE;
b = 1;
b = true;
In the fixed example, the code defines its own values for the Boolean true and false, so the code can be ported without problems.