Integer Underflow (Wrap or Wraparound)

The product subtracts one value from another, such that the result is less than the minimum allowable integer value, which produces a value that is not equal to the correct result.


Description

This can happen in signed and unsigned cases.

Demonstrations

The following examples help to illustrate the nature of this weakness and describe methods or techniques which can be used to mitigate the risk.

Note that the examples here are by no means exhaustive and any given weakness may have many subtle varieties, each of which may require different detection methods or runtime controls.

Example One

The following example subtracts from a 32 bit signed integer.

#include <stdio.h>
#include <stdbool.h>
main (void)
{
  int i;
  i = -2147483648;
  i = i - 1;
  return 0;
}

The example has an integer underflow. The value of i is already at the lowest negative value possible, so after subtracting 1, the new value of i is 2147483647.

Example Two

This code performs a stack allocation based on a length calculation.

int a = 5, b = 6;
size_t len = a - b;
char buf[len];    // Just blows up the stack
}

Since a and b are declared as signed ints, the "a - b" subtraction gives a negative result (-1). However, since len is declared to be unsigned, len is cast to an extremely large positive number (on 32-bit systems - 4294967295). As a result, the buffer buf[len] declaration uses an extremely large size to allocate on the stack, very likely more than the entire computer's memory space.

Miscalculations usually will not be so obvious. The calculation will either be complicated or the result of an attacker's input to attain the negative value.

See Also

Comprehensive Categorization: Incorrect Calculation

Weaknesses in this category are related to incorrect calculation.

SEI CERT C Coding Standard - Guidelines 04. Integers (INT)

Weaknesses in this category are related to the rules and recommendations in the Integers (INT) section of the SEI CERT C Coding Standard.

SEI CERT Oracle Secure Coding Standard for Java - Guidelines 03. Numeric Types and Operations (NUM)

Weaknesses in this category are related to the rules and recommendations in the Numeric Types and Operations (NUM) section of the SEI CERT Oracle Secure Coding Standar...

Comprehensive CWE Dictionary

This view (slice) covers all the elements in CWE.

CWE Cross-section

This view contains a selection of weaknesses that represent the variety of weaknesses that are captured in CWE, at a level of abstraction that is likely to be useful t...

Weaknesses Introduced During Implementation

This view (slice) lists weaknesses that can be introduced during implementation.


Common Weakness Enumeration content on this website is copyright of The MITRE Corporation unless otherwise specified. Use of the Common Weakness Enumeration and the associated references on this website are subject to the Terms of Use as specified by The MITRE Corporation.