...
INT31-EX2: Conversion from any integer type with a value between SCHAR_MIN
and UCHAR_MAX
into to a character type is permitted if provided the value is used to represent a character rather than a mathematical numberand not an integer.
Conversions to unsigned character types are well-defined by C to have modular behavior. A character's value is not misinterpreted by the loss of sign or conversion to a negative number. For example, the Euro symbol €
is sometimes represented by bit pattern 0x80
which can have the mathematical numerical value 128 or -127 depending on the signedness of the type.
Conversions to signed character types are more problematic.
...
Code Block |
---|
int i = 128; /* 1000 0000 in binary */
assert( SCHAR_MAX == 127);
signed char c = i; /* can trap */
|
...
CERT C Secure Coding Standard | DCL03-C. Use a static assertion to test the value of a constant expression INT18-C. Evaluate integer expressions in a larger size before comparing or assigning to that size |
CERT C++ Secure Coding Standard | INT31-CPP. Ensure that integer conversions do not result in lost or misinterpreted data |
CERT Oracle Secure Coding Standard for Java | NUM12-J. Ensure conversions of numeric types to narrower types do not result in lost or misinterpreted data |
ISO/IEC TR 24772:2013 | Numeric Conversion Errors [FLC] |
MISRA C:2012 | Rule 10.1 (required) |
MITRE CWE | CWE-192, Integer coercion error CWE-197, Numeric truncation error CWE-681, Incorrect conversion between numeric types |
Bibliography
[Derek Jones 2013] | Section 6.2.6.2, "Integer types" |
[Dowd 2006] | Chapter 6, "C Language Issues" ("Type Conversions," pp. 223–270) |
[ISO/IEC 9899:2011] | Subclause 6.3.1.3, "Signed and Unsigned Integers" |
[Seacord 2013] | Chapter 5, "Integer Security" |
[Viega 2005] | Section 5.2.9, "Truncation Error" Section 5.2.10, "Sign Extension Error" Section 5.2.11, "Signed to Unsigned Conversion Error" Section 5.2.12, "Unsigned to Signed Conversion Error" |
[Warren 2002] | Chapter 2, "Basics" |
[xorl 2009] | "CVE-2009-1376: Pidgin MSN SLP Integer Truncation" |
...