Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added Zeljko Brba's examples

...

Include Page
c:INT02 Example
c:INT02 Example

Non-Compliant Code Example (Comparison)

Here is an example that illustrates the idiosyncracies of integer promotion.

Code Block
bgColor#FFcccc

int x = -1;
unsigned y = 1;
printf("%d\n", x < y);

In this example, the comparison operator operates on a{{signed int}} and an unsigned int. By the conversion rules, x is converted to an unsigned int. Since -1 can't be represented as an unsigned int value, and overflows are treated modularly on unsigned int}}s, the {{-1 is converted to UINT_MAX. The upshot is that the program prints 0, because UINT_MAX is not less than 1.

Compliant Solution

The previous example can be modified to produce the intuitive result by forcing the comparison to be done with {{signed int}}s.

Code Block
bgColor#FFcccc

int x = -1;
unsigned y = 1;
printf("%d\n", x < (int) y);

This program prints 1 as expected.

Risk Assessment

Misunderstanding integer conversion rules can lead to errors, which in turn can lead to exploitable vulnerabilities.

...