Integer constant overflow

Constant value falls outside range of integer data type

Description

This defect occurs when you assign a compile-time constant to a signed integer variable whose data type cannot accommodate the value. An n-bit signed integer holds values in the range [-2n-1, 2n-1-1].

For instance, c is an 8-bit signed char variable that cannot hold the value 255.

signed char c = 255;

To determine the sizes of fundamental types, Bug Finder uses your specification for Target processor type (-target).

Risk

The default behavior for constant overflows can vary between compilers and platforms. Retaining constant overflows can reduce the portability of your code.

Even if your compilers wraps around overflowing constants with a warning, the wrap-around behavior can be unintended and cause unexpected results.

Fix

Check if the constant value is what you intended. If the value is correct, use a different, possibly wider, data type for the variable.

Examples

expand all

#define MAX_UNSIGNED_CHAR 255 
#define MAX_SIGNED_CHAR 127

void main() {
    char c1 = MAX_UNSIGNED_CHAR;
    char c2 = MAX_SIGNED_CHAR+1;
}

In this example, the defect appears on the macros because at least one use of the macro causes an overflow. To reproduce these defects, use a Target processor type (-target) where char is signed by default.

Correction — Use Different Data Type

One possible correction is to use a different data type for the variables that overflow.

#define MAX_UNSIGNED_CHAR 255 
#define MAX_SIGNED_CHAR 127

void main() {
    unsigned char c1 = MAX_UNSIGNED_CHAR;
    unsigned char c2 = MAX_SIGNED_CHAR+1;
}

Result Information

Group: Numerical
Language: C | C++
Default: Off
Command-Line Syntax: INT_CONSTANT_OVFL
Impact: Medium
CWE ID: 128, 189, 190, 191
Introduced in R2018b