You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 31 Next »

The three types char, signed char, and unsigned char are collectively called the character types. Compilers have the latitude to define char to have the same range, representation, and behavior as either signed char or unsigned char. Irrespective of the choice made, char is a separate type from the other two and is not compatible with either.

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-A. Represent characters using an appropriate type) more more information on representing characters.

Non-Compliant Code Example

In this non-compliant 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.

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.

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.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

INT07-A

2 (medium)

2 (probable)

2 (medium)

P8

L2

Automated Detection

The LDRA tool suite V 7.6.0 is able to detect violations of this recommendation.

Fortify SCA Version 5.0 with the CERT C Rule Pack can detect violations of this recommendation.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

[[ISO/IEC 9899-1999]] Section 6.2.5, "Types"
[[MISRA 04]] Rule 6.2, "Signed and unsigned char type shall be used only for the storage and use of numeric values"


INT06-A. 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

  • No labels