Main Content

Unsigned integer constant overflow

Constant value falls outside range of unsigned integer data type

Description

This defect occurs in the following cases:

  • You assign a compile-time constant to an unsigned integer variable whose data type cannot accommodate the value.

  • You use an enum value that cannot be accommodated by the underlying type of the enum (and the underlying type is unsigned).

An n-bit unsigned integer holds values in the range [0, 2n-1]. For instance, c is an 8-bit unsigned char variable that cannot hold the value 256.

unsigned char c = 256;

This defect checker depends on the following options:

You do not see the defect in these situations:

  • Creation of new constants from const variables (for specific compilers only).

    Different compilers might define compile-time constants differently. In the following code, c+1u is considered a compile time-constant by GCC compilers, but not by the standard C compiler:

    const uint16_t c = 0xffffu;
    uint16_t y = c + 1u;
    Whether you see a violation of this check on y might depend on your compiler.

  • Bitwise NOT operation.

    Polyspace® does not raise this violation when you perform a bitwise NOT operation.

Risk

The C standard states that overflowing unsigned integers must be wrapped around (see, for instance, the C11 standard, section 6.2.5). However, 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 wider data type for the variable.

Examples

expand all

#define MAX_UNSIGNED_CHAR 255
#define MAX_UNSIGNED_SHORT 65535

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

In this example, the defect appears on the macros because at least one use of the macro causes an overflow.

Correction — Use Wider Data Type

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

#define MAX_UNSIGNED_CHAR 255
#define MAX_UNSIGNED_SHORT 65535

void main() {
    unsigned short c1 = MAX_UNSIGNED_CHAR + 1;
    unsigned int c2 = MAX_UNSIGNED_SHORT + 1;
}

Result Information

Group: Numerical
Language: C | C++
Default: Off
Command-Line Syntax: UINT_CONSTANT_OVFL
Impact: Low

Version History

Introduced in R2018b