Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
int si = /* some signed value */;
unsigned ui = /* some unsigned value */;
printf("%d\n", (si < 0 || (unsigned)si < ui));

Noncompliant Code Example

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

Code Block
bgColor#FFcccc

uint8_t port = 0x5a;
uint8_t result_8 = ( ~port ) >> 4;

In this example, a bitwise complement of port is first computed and then shifted 4 bits to the right. If both of these operations are performed on an 8-bit unsigned integer, then result_8 will have the value 0x0a. However, port is first promoted to a signed int, with the following results (on a typical architecture where type int is 32 bits wide):

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, the bitwise complement of port is converted back to 8 bits. Consequently, result_8 is assigned the expected value of 0x0aU.

Code Block
bgColor#ccccff

uint8_t port = 0x5a;
uint8_t result_8 = (uint8_t) (~port) >> 4;

Risk Assessment

Misunderstanding integer conversion rules can lead to errors, which in turn can lead to exploitable vulnerabilities. The major risks occur when narrowing the type (which requires a specific cast or assignment), converting from unsigned to signed, or converting from negative to unsigned.

...