...
Use only signed char
and unsigned char
types for the storage and use of numeric values, as this is the only portable way to guarantee the signedness of the character types. See STR00-AC. Represent characters using an appropriate type for more information on representing characters.
...
Noncompliant Code Example
In this non-compliant noncompliant code example, the char
-type variable c
may be signed or unsigned. Assuming 8-bit, 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); |
Exceptions
INT07-EX1: FIO34-C. Use int to capture the return value of character IO functions mentions that certain character IO functions return a value of type int
. Despite being returned in an arithmetic type, the value is not actually numeric in nature so it is acceptable to later store the result into a variable of type char
.
Risk Assessment
This is a subtle error that results in a disturbingly broad range of potentially severe vulnerabilities. At the very least, this error can lead to unexpected numerical results on different platforms. Unexpected arithmetic values when applied to arrays or pointers can yield buffer overflows or other invalid memory access.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
INT07-A C | medium | probable | medium | P8 | L2 |
Automated Detection
The LDRA tool suite V 7.6.0 can detect violations of this recommendation.
...
Compass/ROSE can detect violations of this recommendation. In particular, it flags any instance of a variable of type char
(without a signed
or unsigned
qualifier) that appears in an arithmetic expression.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.2.5, "Types" \[[ISO/IEC PDTR 24772|AA. C References#ISO/IEC PDTR 24772]\] "STR Bit Representations" \[[MISRA 04|AA. C References#MISRA 04]\] Rule 6.2, "Signed and unsigned char type shall be used only for the storage and use of numeric values" |
...
INT06-C. Use strtol() or a related function to convert a string token to an integer 04. Integers (INT) INT08-A. Verify that all integer values are in range