...
| Code Block | ||
|---|---|---|
| ||
int xsi = -1; unsigned yui = 1; printf("%d\n", xsi < yui); |
In this example, the comparison operator operates on a signed int and an unsigned int. By the conversion rules, x si is converted to an unsigned int. Because -1 cannot be represented as an unsigned int value, and unsigned int is treated modularly, the -1 is converted to UINT_MAX. Consequently, the program prints 0, because UINT_MAX is not less than 1.
...
| Code Block | ||
|---|---|---|
| ||
int xsi = -1; unsigned yui = 1; printf("%d\n", xsi < (int) yui); |
This program prints 1 as expected. Note that (int)y is only correct in this case because the value of ui is known to be representable as an int. If this were not known, the compliant solution would need to be written as:
| Code Block | ||
|---|---|---|
| ||
int si = /* some signed value */;
unsigned ui = /* some unsigned value */;
printf("%d\n", (si < 0 || (unsigned)si < ui));
|
Risk Assessment
Misunderstanding integer conversion rules can lead to errors, which in turn can lead to exploitable vulnerabilities.
...