Integer conversions, both implicit and explicit (using a cast), must be guaranteed not to result in lost or misinterpreted data. This rule is particularly true for integer values that originate from untrusted sources and are used in any of the following ways:
- Integer operands of any pointer arithmetic, including array indexing;
- The assignment expression for the declaration of a variable length array;
- The postfix expression preceding square brackets
[]
or the expression in square brackets[]
of a subscripted designation of an element of an array object; and - Function arguments of type
size_t
orrsize_t
(for example, an argument to a memory allocation function).
This rule also applies to arguments passed to the following library functions that are converted to unsigned char
:
memset()
memset_s()
fprintf()
and related functions (For the length modifierc
, if nol
length modifier is present, theint
argument is converted to anunsigned char
, and the resulting character is written.)fputc()
ungetc()
memchr()
and to arguments to the following library functions that are converted to char
:
strchr()
strrchr()
- All of the functions listed in
<ctype.h>
The only integer type conversions that are guaranteed to be safe for all data values and all possible conforming implementations are conversions of an integral value to a wider type of the same signedness. The C Standard, subclause 6.3.1.3 [ISO/IEC 9899:2011], says,
When a value with integer type is converted to another integer type other than
_Bool
, if the value can be represented by the new type, it is unchanged.Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
Typically, converting an integer to a smaller type results in truncation of the high-order bits.
Noncompliant Code Example (Unsigned to Signed)
Type range errors, including loss of data (truncation) and loss of sign (sign errors), can occur when converting from a value of an unsigned integer type to a value of a signed integer type. This noncompliant code example results in a truncation error on most implementations:
#include <limits.h> void func(void) { unsigned long int u_a = ULONG_MAX; signed char sc; sc = (signed char)u_a; /* Cast eliminates warning */ /* ... */ }
Compliant Solution (Unsigned to Signed)
Validate ranges when converting from an unsigned type to a signed type. This compliant solution can be used to convert a value of unsigned long int
type to a value of signed char
type:
#include <limits.h> void func(void) { unsigned long int u_a = ULONG_MAX; signed char sc; if (u_a <= SCHAR_MAX) { sc = (signed char)u_a; /* Cast eliminates warning */ } else { /* Handle error */ } }
Noncompliant Code Example (Signed to Unsigned)
Type range errors, including loss of data (truncation) and loss of sign (sign errors), can occur when converting from a value of a signed type to a value of an unsigned type. This noncompliant code example results in a loss of sign:
#include <limits.h> void func(void) { signed int si = INT_MIN; /* Cast eliminates warning */ unsigned int ui = (unsigned int)si; /* ... */ }
Compliant Solution (Signed to Unsigned)
Validate ranges when converting from a signed type to an unsigned type. This compliant solution converts a value of a signed int
type to a value of an unsigned int
type:
#include <limits.h> void func(void) { signed int si = INT_MIN; unsigned int ui; if (si < 0) { /* Handle error */ } else { ui = (unsigned int)si; /* Cast eliminates warning */ } /* ... */ }
Subclause 6.2.5, paragraph 9, of the C Standard [ISO/IEC 9899:2011] provides the necessary guarantees to ensure this solution works on a conforming implementation:
The range of nonnegative values of a signed integer type is a subrange of the corresponding unsigned integer type, and the representation of the same value in each type is the same.
Noncompliant Code Example (Signed, Loss of Precision)
A loss of data (truncation) can occur when converting from a value of a signed integer type to a value of a signed type with less precision. This noncompliant code example results in a truncation error on most implementations:
#include <limits.h> void func(void) { signed long int s_a = LONG_MAX; signed char sc = (signed char)s_a; /* Cast eliminates warning */ /* ... */ }
Compliant Solution (Signed, Loss of Precision)
Validate ranges when converting from a signed type to a signed type with less precision. This compliant solution converts a value of a signed long int
type to a value of a signed char
type:
#include <limits.h> void func(void) { signed long int s_a = LONG_MAX; signed char sc; if ((s_a < SCHAR_MIN) || (s_a > SCHAR_MAX)) { /* Handle error */ } else { sc = (signed char)s_a; /* Use cast to eliminate warning */ } /* ... */ }
Conversions from a value of a signed integer type to a value of a signed integer type with less precision requires that both the upper and lower bounds are checked.
Noncompliant Code Example (Unsigned, Loss of Precision)
A loss of data (truncation) can occur when converting from a value of an unsigned integer type to a value of an unsigned type with less precision. This noncompliant code example results in a truncation error on most implementations:
#include <limits.h> void func(void) { unsigned long int u_a = ULONG_MAX; unsigned char uc = (unsigned char)u_a; /* Cast eliminates warning */ /* ... */ }
Compliant Solution (Unsigned, Loss of Precision)
Validate ranges when converting a value of an unsigned integer type to a value of an unsigned integer type with less precision. This compliant solution converts a value of an unsigned long int
type to a value of an unsigned char
type:
#include <limits.h> void func(void) { unsigned long int u_a = ULONG_MAX; unsigned char uc; if (u_a > UCHAR_MAX) { /* Handle error */ } else { uc = (unsigned char)u_a; /* Cast eliminates warning */ } /* ... */ }
Conversions from unsigned types with greater precision to unsigned types with less precision require only the upper bounds to be checked.
Noncompliant Code Example (time_t
Return Value)
The time()
function returns the value (time_t)(-1)
to indicate that the calendar time is not available. The C Standard requires only that the time_t
type is a real type capable of representing time. (The integer and real floating types are collectively called real types.) It is left to the implementor to decide the best real type to use to represent time. If time_t
is implemented as an unsigned integer type with less precision than a signed int
, the return value of time()
will never compare equal to the integer literal -1
.
#include <time.h> void func(void) { time_t now = time(NULL); if (now != -1) { /* Continue processing */ } }
Compliant Solution (time_t
Return Value)
To ensure the comparison is properly performed, the return value of time()
should be compared against -1
cast to type time_t
:
#include <time.h> void func(void) { time_t now = time(NULL); if (now != (time_t)-1) { /* Continue processing */ } }
This solution is in accordance with INT18-C. Evaluate integer expressions in a larger size before comparing or assigning to that size.
Noncompliant Code Example (memset()
)
For historical reasons, certain C Standard functions accept an argument of type int
and convert it to either unsigned char
or plain char
. This conversion can result in unexpected behavior if the value cannot be represented in the smaller type. This noncompliant solution unexpectedly clears the array:
#include <string.h> #include <stddef.h> int *init_memory(int *array, size_t n) { return memset(array, 4096, n); }
Compliant Solution (memset())
In general, the memset()
function should not be used to initialize an integer array unless it is to set or clear all the bits, as in this compliant solution:
#include <string.h> #include <stddef.h> int *init_memory(int *array, size_t n) { return memset(array, 0, n); }
Exceptions
INT31-C-EX1: The C Standard defines minimum ranges for standard integer types. For example, the minimum range for an object of type unsigned short int
is 0 to 65,535, whereas the minimum range for int
is −32,767 to +32,767. Consequently, it is not always possible to represent all possible values of an unsigned short int
as an int
. However, on the IA-32 architecture, for example, the actual integer range is from −2,147,483,648 to +2,147,483,647, meaning that it is quite possible to represent all the values of an unsigned short int
as an int
for this architecture. As a result, it is not necessary to provide a test for this conversion on IA-32. It is not possible to make assumptions about conversions without knowing the precision of the underlying types. If these tests are not provided, assumptions concerning precision must be clearly documented, as the resulting code cannot be safely ported to a system where these assumptions are invalid. A good way to document these assumptions is to use static assertions (see DCL03-C. Use a static assertion to test the value of a constant expression).
INT31-C-EX2: Conversion from any integer type with a value between SCHAR_MIN
and UCHAR_MAX
to a character type is permitted provided the value represents a character and 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 numerical value 128 or −127 depending on the signedness of the type.
Conversions to signed character types are more problematic. The C Standard, subclause 6.3.1.3, paragraph 3 [ISO/IEC 9899:2011], says, regarding conversions:
Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
Furthermore, subclause 6.2.6.2, paragraph 2, says, regarding integer modifications:
If the sign bit is one, the value shall be modified in one of the following ways:
— the corresponding value with sign bit 0 is negated (sign and magnitude)
— the sign bit has the value −(2M ) (two’s complement);
— the sign bit has the value −(2M − 1) (ones’ complement).
Which of these applies is implementation-defined, as is whether the value with sign bit 1 and all value bits zero (for the first two), or with sign bit and all value bits 1 (for ones’ complement), is a trap representation or a normal value. [See note.]
NOTE: Two's complement is shorthand for "radix complement in radix 2." Ones' complement is shorthand for "diminished radix complement in radix 2."
Consequently, the standard allows for this code to trap:
int i = 128; /* 1000 0000 in binary */ assert(SCHAR_MAX == 127); signed char c = i; /* can trap */
However, platforms where this code traps or produces an unexpected value are rare. According to The New C Standard: An Economic and Cultural Commentary by Derek Jones [Jones 2008]:
Implementations with such trap representations are thought to have existed in the past. Your author was unable to locate any documents describing such processors.
Risk Assessment
Integer truncation errors can lead to buffer overflows and the execution of arbitrary code by an attacker.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
INT31-C | High | Probable | High | P6 | L2 |
Automated Detection
Tool | Version | Checker | Description |
---|---|---|---|
CodeSonar | 8.1p0 | ALLOC.SIZE.TRUNC | Truncation of allocation size |
Can detect violations of this rule. However, false warnings may be raised if | |||
2017.07 | NEGATIVE_RETURNS
| Can find array accesses, loop bounds, and other expressions that may contain dangerous implied integer conversions that would result in unexpected behavior Can find instances where a negativity check occurs after the negative value has been used for something else Can find instances where an integer expression is implicitly converted to a narrower integer type, where the signedness of an integer value is implicitly converted, or where the type of a complex expression is implicitly converted | |
Cppcheck | 2.15 | memsetValueOutOfRange | The second argument to memset() cannot be represented as unsigned char |
5.0 | Can detect violations of this rule with CERT C Rule Pack | ||
2024.3 | PRECISION.LOSS | ||
9.7.1 | 93 S, 433 S, 434 S | Partially implemented | |
Polyspace Bug Finder | R2016a | Sign change integer conversion overflow | Overflow when converting between integer types Overflow when converting between signed and unsigned integers
Value from an unsecure source changes sign
Overflow when converting between unsigned integer types |
PRQA QA-C | Unable to render {include} The included page could not be found. | 2850, 2851, 2852, 2853, | Partially implemented |
* Coverity Prevent cannot discover all violations of this rule, so further verification is necessary.
Related Vulnerabilities
CVE-2009-1376 results from a violation of this rule. In version 2.5.5 of Pidgin, a size_t
offset is set to the value of a 64-bit unsigned integer, which can lead to truncation [xorl 2009] on platforms where a size_t
is implemented as a 32-bit unsigned integer. An attacker can execute arbitrary code by carefully choosing this value and causing a buffer overflow.
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
SEI CERT C Coding Standard | DCL03-C. Use a static assertion to test the value of a constant expression |
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
[Dowd 2006] | Chapter 6, "C Language Issues" ("Type Conversions," pp. 223–270) |
[ISO/IEC 9899:2011] | 6.3.1.3, "Signed and Unsigned Integers" |
[Jones 2008] | Section 6.2.6.2, "Integer Types" |
[Seacord 2013b] | 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" |