...
In this non-compliant code example, the char
-type variables variable c
may be signed or unsigned. Assuming 8-bit, twos two's complement character types, this code may either print out i/c = 5
(unsigned) or i/c = -17
(signed). As a result, it is much more difficult to reason about the correctness of a program without knowing if these integers are signed or unsigned.
Code Block | ||
---|---|---|
| ||
char c = 200;
int i = 1000;
printf("i/c = %d\n", i/c);
|
Compliant Solution
In this compliant solution, the variable c
is declared as unsigned char
. The subsequent division operation is now independent of the signedness of char
and consequently has a predictable result.
Code Block | ||
---|---|---|
| ||
unsigned char c = 200;
int i = 1000;
printf("i/c = %d\n", i/c);
|
Risk Assessment
This is a subtle error that results in a disturbingly broad range of potentially severe vulnerabilities.
...
Wiki Markup |
---|
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.2.5, "Types" \[[MISRA 04|AA. C References#MISRA 04]\] Rule 6.2, "signedSigned and unsigned char type shall be used only for the storage and use of numeric values." |