CERT-INT31-C_a
Synopsis
Ensure that integer conversions do not result in lost or misinterpreted data.
Enabled by default
Yes
Severity/Certainty
High/Medium

Full description
Integer conversions, both implicit and explicit (using a cast), must be guaranteed not to result in lost or misinterpreted data. This is particularly true for integer values that originate from untrusted sources and are used in pointer arithmetic, variable length array declaration, array subscription, and library function arguments that are of unsigned char types or represent sizes. This check is identical to ATH-overflow-cast.
Coding standards
- CERT INT31-C
Ensure that integer conversions do not result in lost or misinterpreted data
- CWE 192
Integer Coercion Error
- CWE 194
Unexpected Sign Extension
- CWE 195
Signed to Unsigned Conversion Error
- CWE 197
Numeric Truncation Error
- CWE 681
Incorrect Conversion between Numeric Types
- CWE 704
Incorrect Type Conversion or Cast
Code examples
The following code example fails the check and will give a warning:
#include <limits.h>
void example(void) {
unsigned long int u_a = ULONG_MAX;
signed char sc;
sc = (signed char)u_a; /* Cast eliminates warning */
/* ... */
}
The following code example passes the check and will not give a warning about this issue:
#include <limits.h>
void example(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 */
}
}