Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: i just realized the noncompliant code example is for uint8_t while the rule was about char and short. changed rule title to be integer types shorter than int

Integer types smaller than int are promoted when an operation is performed on them. If all values of the original type can be represented as an int, the value of the smaller type is converted to an int; otherwise, it is converted to an unsigned int (see INT02-C. Understand integer conversion rules). If the conversion is to a wider type, the original value is zero-extended for unsigned values or sign-extended for signed types. Arithmetic operations performed on ints yield the same values as on chars and shorts (at least in the low-order bits). However, bitwise operations may have unexpected results.

Noncompliant Code Example

This noncompliant code example demonstrates how performing bitwise operations on integer types smaller than int may have unexpected results.

...

Expression

Type

Value

Notes

port

uint8_t

0x5a

 

~port

int

0xffffffa5

 

~port >> 4

int

0x0ffffffa

Whether or not value is negative is implementation-defined.

result_8

uint8_t

0xfa

 

Compliant Solution

In this compliant solution, we truncate the negation back down to 8 bits. Consequently, result_8 receives the expected value of 0x0aU.

Code Block
bgColor#ccccff
uint8_t port = 0x5a;
uint8_t result_8 = (uint8_t) (~port) >> 4;

Risk Assessment

Bitwise operations on shorts and chars can produce incorrect data.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

EXP14-C

low

likely

high

P3

L3

Automated Detection

Tool

Version

Checker

Description

Section

Compass/ROSE

 

 

 

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

CERT C++ Secure Coding Standard: EXP15-CPP. Beware of integer promotion when performing bitwise operations on chars or shorts

MISRA Rule 10.5

Bibliography

...

      03. Expressions (EXP)