Constant subtraction wraps around when stored into an unsigned type
ID |
c.correctness.unsigned_constant_wraparound |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Numeric Operation |
Language |
C / C++ |
Description
This subtraction of two constants is negative, but the result is stored into an unsigned variable, so it silently wraps around to a very large positive value instead. Swap the operands, use a signed type, or write the intended constant directly rather than deriving it from a subtraction that underflows.
Rationale
This subtraction of two constants is negative, but the result is stored into an unsigned variable, so it silently wraps around to a very large positive value instead. Swap the operands, use a signed type, or write the intended constant directly rather than deriving it from a subtraction that underflows.
The following code illustrates the pattern detected by this rule:
void configure(void)
{
unsigned int a;
// FLAGGED: Constant subtraction wraps around when stored into an unsigned type
a = 5 - 10;
a = 10 - 5;
unsigned long b;
// FLAGGED: Constant subtraction wraps around when stored into an unsigned type
b = 0 - 1;
b = 20 - 20;
int signedVal;
signedVal = 5 - 10;
}
Remediation
Follow secure coding practices and review the references below for detailed remediation guidance.