Weaknesscore
Integer overflow or wraparound
Also called integer overflow, integer wraparound, wraparound, cwe-190.
An integer overflow happens when a calculation produces a value that does not fit in its integer type, so the program continues with a wrapped, truncated or undefined result that it treats as correct.
- CWE
- CWE-190
- Abstraction
- base
- Languages affected
- c, cpp, csharp, go, java, kotlin, rust, javascript
Description
A machine integer has a fixed number of bits. A 32-bit int holds values from −2,147,483,648 to 2,147,483,647, and nothing more. Arithmetic in a program looks like arithmetic in mathematics, but the result must fit in the type. An integer overflow happens when it does not fit. The result wraps around to a small or negative value, or it is truncated, and the program goes on as if the value were correct.1 An underflow is the same error in the other direction, below the minimum. CWE files it as CWE-191.1
The root cause is the distance between the integers of mathematics and the integers of the machine. The code says price * quantity, and the developer thinks of the product. The machine computes the product modulo 2³² or 2⁶⁴. The two agree for every value that a test is likely to use, so the bug stays hidden until an input is large. blexim wrote in 2002 that an overflow cannot be detected after it happens, so the program has no way to tell if a result is correct.4 The check must come before the operation, and a check written after it, such as if (total < 0), is too late and often wrong.
Each language defines the result differently. In C and C++, unsigned arithmetic wraps modulo 2ⁿ. Signed overflow is undefined behavior, so a conforming compiler may do anything, from ignoring the overflow to aborting the program.4 Go, Java, Kotlin and C# in its default context wrap signed values.9202111 Rust panics in a debug build and wraps in a release build.7 Python integers have unlimited precision.12 JavaScript numbers are doubles, which lose exact integers above 2⁵³ − 1.14
The wrapped value is dangerous because of what the program does with it next. CWE-190 says that the weakness becomes a security problem when the result controls a loop, a security decision such as a quota or a limit, or the size of an allocation or a copy.1 A size that wraps to a small value makes a small buffer, and the copy that follows writes past its end. CWE-680 names this chain, and the page Out-of-bounds write shows the write. A time value that wraps can make an expiry check fail. CWE-190 lists the Year 2038 problem as an alternate term: some 32-bit time values on Unix-related systems overflow on January 19, 2038.1
CWE-190 is a base weakness under CWE-682, incorrect calculation. It lists C as a language where it is often prevalent.1 It is not in the 2025 CWE Top 25. It is rank 30 on the list of weaknesses on the cusp, with 2 CVEs in the CISA catalogue of known exploited vulnerabilities, down from rank 23 the year before.2 The OWASP Top 10:2025 maps it to X02:2025 Memory Management Failures, a category in its Next Steps section and not in the ten.3
History
In December 2002, Phrack 60 published "Basic Integer Overflows" by blexim.4 It described integer overflows and signedness bugs in C as classes of bugs that put unexpected values in variables, not bugs that overwrite memory directly. It said that most of them are not exploitable, that they can lead to other bugs, frequently buffer overflows, and that they are hard to spot, so even well audited code can contain them.4 In the same year, CVE-2002-0639 recorded an integer overflow in the challenge response authentication of OpenSSH that let remote attackers run code.17
Vulnerable code
order_fits checks that an order is inside a budget. The second call uses the classic demonstration input, a quantity so large that the product does not fit in an int. The block builds with UndefinedBehaviorSanitizer, which reports the overflow.5
This code has a memory error, on purpose, and the sanitizer reports it.
#include <stdio.h>
// Returns 1 if the order costs no more than the budget.
int order_fits(int price, int quantity, int budget) {
int total = price * quantity; // can overflow
return total <= budget;
}
int main(void) {
printf("3 items: %d\n", order_fits(100, 3, 1000));
printf("42949673 items: %d\n", order_fits(100, 42949673, 1000));
}
UndefinedBehaviorSanitizer reports signed integer overflow: 100 * 42949673 cannot be represented in type 'int'. The true product is 4,294,967,300. If the multiplication wraps modulo 2³², the result is 4, and the order of forty million items fits in a budget of 1,000. The behavior is undefined, so the standard does not promise even that. Nothing in the output says that the result was wrong.
Fixed code
The fix checks the operands before the multiplication. A product of two positive values fits only if price is not greater than INT_MAX / quantity. The block builds with AddressSanitizer and UndefinedBehaviorSanitizer, and both stay silent.
#include <limits.h>
#include <stdio.h>
// Returns 1 if the order costs no more than the budget.
// Price and quantity must not be negative.
int order_fits(int price, int quantity, int budget) {
if (price < 0 || quantity < 0) {
return 0;
}
if (quantity != 0 && price > INT_MAX / quantity) {
return 0; // the total does not fit in an int
}
int total = price * quantity;
return total <= budget;
}
int main(void) {
printf("3 items: %d\n", order_fits(100, 3, 1000));
printf("42949673 items: %d\n", order_fits(100, 42949673, 1000));
}
3 items: 1
42949673 items: 0
The check rejects negative values first, as CWE-190 asks: a range check must test the minimum and the maximum.1 The header <stdckdint.h> of C has ckd_add, ckd_sub and ckd_mul. Each one computes the result as if the type had infinite range, stores the wrapped value and returns true when the value does not fit.6 The C example file shows ckd_mul.
Checked arithmetic in other languages
Every language with fixed-width integer types has the same limit. The languages differ in what happens by default and in how much work the check takes.
Rust checks for overflow in a debug build. The program below panics with attempt to multiply with overflow.
This code panics, on purpose.
fn order_fits(price: i32, quantity: i32, budget: i32) -> bool {
let total = price * quantity;
total <= budget
}
fn main() {
println!("3 items: {}", order_fits(100, 3, 1000));
println!("42949673 items: {}", order_fits(100, 42949673, 1000));
}
The Rust book says that a release build does not include these checks and wraps the value in two's complement, and that relying on the wrap is an error.7 The Rust reference calls overflow a programmer error, not undefined behavior.8 The checked_* methods return None on overflow in every build, and the Rust example file uses checked_mul for the fix.7
In Java, Math.multiplyExact and Math.addExact throw ArithmeticException when the result overflows.10 In C#, a checked block or expression throws System.OverflowException. The default context is unchecked, and it discards the high-order bits.11 The Go specification says that signed overflow does not cause a run-time panic and that a compiler may not assume that x < x + 1 is always true, so Go code must check the operands itself.9 Each example file shows the silent wrap and the check.
How to detect it
- Sanitizers. Build the tests with
-fsanitize=undefined. Its checksigned-integer-overflowreports signed overflow, includingINT_MIN / -1. The checkunsigned-integer-overflowreports unsigned wraps. They are not undefined behavior, but they are often unintentional, so this check is not in the default set.5 - Fuzzing. CWE-190 rates fuzzing as moderately effective.1 A fuzzer finds the large values that hand-written tests skip, and the sanitizer turns each overflow into a failure.
- Static analysis. CWE-190 rates automated static analysis as highly effective.1 CodeQL query
cpp/uncontrolled-arithmeticfinds arithmetic on data from outside the program with no guard.15 Querycpp/integer-multiplication-cast-to-longfinds a product that is converted to a larger type after the multiplication, when the overflow has already happened.16 - Code review. For each calculation of a size, a count, an index, an amount of money or a time, find the largest input and work out the result. Look for
malloc(n * size),len + 1, subtraction of unsigned values, and casts between signed and unsigned types.
How to prevent it
- Choose types and languages that check. CWE-190 lists language selection first. Python integers do not overflow.12 Rust checks in debug builds, and checked APIs exist in Java, C# and C.710116
- Use checked operations for values from input. Use
ckd_mul,checked_mul,Math.multiplyExactor acheckedblock, and handle the failure. CWE-190 also names safe integer libraries such as SafeInt for C++.1 - Validate the range of input. Check the minimum and the maximum of each numeric input before any arithmetic, against limits that come from the problem, not from the type.1
- Know the representation. Learn the width of each type, the rules for signed and unsigned conversion, and the behavior on overflow of the language. CWE-190 links this to CWE-681, incorrect conversion between numeric types.1
- Treat compiler warnings as errors. CWE-190 says to examine compiler warnings closely, such as a signed and unsigned mismatch in a memory operation.1
Real cases
| Case | Date | What happened |
|---|---|---|
| CVE-2002-0639 | published 2003-04-02 | An integer overflow in sshd in OpenSSH 2.9.9 through 3.3 let remote attackers run code during challenge response authentication with SKEY or BSD_AUTH.17 |
| CVE-2021-30860 | published 2021-08-24 | An integer overflow in Apple operating systems let a crafted PDF run code. Apple was aware of a report that it may have been actively exploited.181 |
| CVE-2025-27363 | published 2025-03-11 | FreeType 2.13.0 and earlier assigned a signed short value to an unsigned long and added a constant, so the size wrapped around and the heap buffer was too small. The code then wrote out of bounds. It may have been exploited in the wild.191 |
def order_fits(price, quantity, budget):
return price * quantity <= budget
print("3 items:", order_fits(100, 3, 1000))
print("42949673 items:", order_fits(100, 42949673, 1000))
print("product:", 100 * 42949673)
3 items: True
42949673 items: False
product: 4294967300
Python integers have unlimited precision, so the product is exact and the check is correct.
This code runs but gives a wrong answer on purpose.
import ctypes
total = 100 * 42949673
print("exact:", total)
print("as c_int32:", ctypes.c_int32(total).value)
exact: 4294967300
as c_int32: 4
The overflow comes back at the edge, when a value goes into a fixed-width type for C code, a file format or a network protocol. The ctypes documentation says that the integer types do no overflow checking.
import struct
total = 100 * 42949673
try:
struct.pack("<i", total)
except struct.error as error:
print("refused:", error)
refused: 'i' format requires -2147483648 <= number <= 2147483647
- Verdict: native.
inthas unlimited precision, so arithmetic on integers does not overflow. ctypes,arrayand libraries for numeric arrays store values in fixed-width types. Check the range before a value goes in.struct.packraisesstruct.errorfor a value that does not fit its format.
This code runs but gives a wrong answer on purpose.
#include <cstddef>
#include <iostream>
#include <vector>
// Returns the number of items after the first skip items.
std::size_t remaining(const std::vector<int>& items, std::size_t skip) {
return items.size() - skip;
}
int main() {
std::vector<int> items{1, 2, 3};
std::cout << remaining(items, 2) << '\n';
std::cout << remaining(items, 5) << '\n';
}
1
18446744073709551614
size() returns an unsigned type. 3 − 5 does not give −2. It wraps to a value near 2⁶⁴, and a loop that uses it as a count runs far past the end of the vector. The behavior is defined, so no sanitizer in the default set reports it.
This code does not compile, on purpose.
#include <cstdint>
#include <iostream>
int main() {
std::int64_t total = 4294967300;
std::int32_t small{total};
std::cout << small << '\n';
}
Brace initialization does not allow a narrowing conversion. Clang rejects the conversion of a 64-bit value to a 32-bit one. GCC rejects a narrowing conversion of a constant, but gives only a warning when the value is not a constant, so this build adds -Werror=narrowing. An initialization with = compiles and truncates the value.
#include <cstddef>
#include <iostream>
#include <optional>
#include <vector>
// Returns the number of items after the first skip items, or nothing.
std::optional<std::size_t> remaining(const std::vector<int>& items, std::size_t skip) {
if (skip > items.size()) {
return std::nullopt;
}
return items.size() - skip;
}
int main() {
std::vector<int> items{1, 2, 3};
for (std::size_t skip : {2, 5}) {
if (auto left = remaining(items, skip)) {
std::cout << "skip " << skip << ": " << *left << '\n';
} else {
std::cout << "skip " << skip << ": more than the size\n";
}
}
}
skip 2: 1
skip 5: more than the size
- Verdict: absent. C++ has the arithmetic rules of C: signed overflow is undefined behavior, and unsigned arithmetic wraps.
- Sizes and indices in the standard library are unsigned, so a subtraction of sizes is a common source of wraparound. Compare before you subtract.
- Brace initialization rejects narrowing conversions at compile time. Use it for conversions between integer types of different widths.
- CWE-190 names SafeInt as a safe integer library for C++. It is a third-party library.
This code runs but gives a wrong answer on purpose.
public class Main {
// Returns true if the order costs no more than the budget.
static boolean orderFits(int price, int quantity, int budget) {
int total = price * quantity; // wraps on overflow
return total <= budget;
}
public static void main(String[] args) {
System.out.println("3 items: " + orderFits(100, 3, 1000));
System.out.println("42949673 items: " + orderFits(100, 42949673, 1000));
}
}
3 items: true
42949673 items: true
The Java Language Specification says that an overflowing multiplication keeps the low-order bits of the product. Here they give 4, and the large order fits.
public class Main {
// Returns true if the order costs no more than the budget.
static boolean orderFits(int price, int quantity, int budget) {
if (price < 0 || quantity < 0) {
return false;
}
try {
return Math.multiplyExact(price, quantity) <= budget;
} catch (ArithmeticException e) {
System.out.println("refused: " + e.getMessage());
return false;
}
}
public static void main(String[] args) {
System.out.println("3 items: " + orderFits(100, 3, 1000));
System.out.println("42949673 items: " + orderFits(100, 42949673, 1000));
}
}
3 items: true
refused: integer overflow
42949673 items: false
- Verdict: stdlib. Arithmetic on
intandlongwraps with no error.Math.addExact,subtractExact,multiplyExact,incrementExact,negateExactandtoIntExactthrowArithmeticExceptionon overflow. java.math.BigIntegerhas no fixed width. Use it when the values have no natural limit.- A cast such as
(int) longValuekeeps the low-order bits. UseMath.toIntExactto get an exception.
This code has a memory error, on purpose, and the sanitizer reports it.
#include <stdio.h>
// Returns 1 if the order costs no more than the budget.
int order_fits(int price, int quantity, int budget) {
int total = price * quantity; // can overflow
return total <= budget;
}
int main(void) {
printf("3 items: %d\n", order_fits(100, 3, 1000));
printf("42949673 items: %d\n", order_fits(100, 42949673, 1000));
}
UndefinedBehaviorSanitizer reports the signed overflow in order_fits. Without the sanitizer, the behavior is undefined. A build that wraps the product gets 4, and the large order fits in the budget.
#include <stdckdint.h>
#include <stdio.h>
// Returns 1 if the order costs no more than the budget.
int order_fits(int price, int quantity, int budget) {
int total;
if (price < 0 || quantity < 0) {
return 0;
}
if (ckd_mul(&total, price, quantity)) {
return 0; // the total does not fit in an int
}
return total <= budget;
}
int main(void) {
printf("3 items: %d\n", order_fits(100, 3, 1000));
printf("42949673 items: %d\n", order_fits(100, 42949673, 1000));
}
3 items: 1
42949673 items: 0
This code runs but gives a wrong answer on purpose.
#include <stdio.h>
int main(void) {
unsigned int stock = 2;
unsigned int sold = 3;
unsigned int left = stock - sold; // wraps to 4294967295
printf("left: %u\n", left);
}
left: 4294967295
Unsigned arithmetic wraps by definition, so the program has no undefined behavior, and the default set of UndefinedBehaviorSanitizer checks does not report it. Clang has the extra check -fsanitize=unsigned-integer-overflow for it. GCC has no such check. This is an underflow, CWE-191: 2 − 3 is not −1 but 4,294,967,295.
- Verdict: absent. C has no overflow check in its arithmetic. Signed overflow is undefined behavior, and unsigned arithmetic wraps modulo 2ⁿ.
ckd_add,ckd_subandckd_mulin<stdckdint.h>compute the result as if the type had infinite range and returntruewhen the stored value is not the true result.- Without
<stdckdint.h>, check the operands before the operation, as in the fixed code of the page:a > INT_MAX / bfor a product of positive values, anda > INT_MAX - bfor a sum. - Never check after the operation. A test such as
if (total < 0)reads a value that the program had no right to compute.
This code runs but gives a wrong answer on purpose.
static bool OrderFits(int price, int quantity, int budget)
{
int total = price * quantity; // wraps on overflow
return total <= budget;
}
Console.WriteLine($"3 items: {OrderFits(100, 3, 1000)}");
Console.WriteLine($"42949673 items: {OrderFits(100, 42949673, 1000)}");
3 items: True
42949673 items: True
The default context is unchecked. The product loses its high-order bits and becomes 4.
static bool OrderFits(int price, int quantity, int budget)
{
if (price < 0 || quantity < 0)
{
return false;
}
try
{
return checked(price * quantity) <= budget;
}
catch (OverflowException e)
{
Console.WriteLine($"refused: {e.Message}");
return false;
}
}
Console.WriteLine($"3 items: {OrderFits(100, 3, 1000)}");
Console.WriteLine($"42949673 items: {OrderFits(100, 42949673, 1000)}");
3 items: True
refused: Arithmetic operation resulted in an overflow.
42949673 items: False
- Verdict: native. A
checkedexpression or block throwsSystem.OverflowExceptionon overflow. An overflow in a constant expression is a compile-time error. - The default context is unchecked, and it discards the high-order bits. The project option
CheckForOverflowUnderflowchanges the default for a whole project. System.Numerics.BigIntegerhas no fixed width.
This code runs but gives a wrong answer on purpose.
function addPoints(balance, points) {
return balance + points;
}
const balance = Number.MAX_SAFE_INTEGER;
console.log(addPoints(balance, 1));
console.log(addPoints(balance, 2));
console.log(addPoints(balance, 1) === addPoints(balance, 2));
9007199254740992
9007199254740992
true
A JavaScript number is a double. Above 2⁵³ − 1, it cannot hold every integer, so two different sums compare as equal.
function addPoints(balance, points) {
const sum = balance + points;
if (!Number.isSafeInteger(sum)) {
throw new RangeError(`the sum is not a safe integer`);
}
return sum;
}
const balance = Number.MAX_SAFE_INTEGER;
console.log(addPoints(100, 1));
try {
addPoints(balance, 2);
} catch (error) {
console.log(`refused: ${error.message}`);
}
console.log(BigInt(balance) + 2n);
101
refused: the sum is not a safe integer
9007199254740993n
- Verdict: idiom. Numbers do not wrap, but integers above
Number.MAX_SAFE_INTEGERlose precision. Check results withNumber.isSafeInteger, or useBigInt, which has no fixed width. - Bitwise operators convert their operands to 32-bit integers, and typed arrays such as
Int32Arraywrap values that do not fit. - Overflow in the engine and in native add-ons, which are written in C and C++, is outside the reach of script.
This code runs but gives a wrong answer on purpose.
package main
import "fmt"
// orderFits reports whether the order costs no more than the budget.
func orderFits(price, quantity, budget int32) bool {
total := price * quantity // wraps on overflow
return total <= budget
}
func main() {
fmt.Println("3 items:", orderFits(100, 3, 1000))
fmt.Println("42949673 items:", orderFits(100, 42949673, 1000))
}
3 items: true
42949673 items: true
The product wraps to 4, so the large order fits. The Go specification says that signed overflow does not cause a run-time panic.
package main
import (
"fmt"
"math"
)
// orderFits reports whether the order costs no more than the budget.
func orderFits(price, quantity, budget int32) bool {
if price < 0 || quantity < 0 {
return false
}
if quantity != 0 && price > math.MaxInt32/quantity {
return false // the total does not fit in an int32
}
return price*quantity <= budget
}
func main() {
fmt.Println("3 items:", orderFits(100, 3, 1000))
fmt.Println("42949673 items:", orderFits(100, 42949673, 1000))
}
3 items: true
42949673 items: false
- Verdict: absent. Go defines the result of overflow: unsigned values wrap modulo 2ⁿ, and signed values wrap in two's complement. There is no run-time check.
- The specification says that a compiler may not assume that
x < x + 1is always true, so a check written in Go is not removed by the optimizer. - Check the operands before the operation, with the constants of the package
math.math/bits.Mul64andbits.Add64return the high word or the carry for unsigned values. - A conversion between integer types, such as
int32(n), truncates silently. Check the range first.
This code panics, on purpose.
fn order_fits(price: i32, quantity: i32, budget: i32) -> bool {
let total = price * quantity;
total <= budget
}
fn main() {
println!("3 items: {}", order_fits(100, 3, 1000));
println!("42949673 items: {}", order_fits(100, 42949673, 1000));
}
A debug build panics with attempt to multiply with overflow. A release build has no such check and wraps the product to 4.
This code does not compile, on purpose.
fn main() {
let count: u8 = 255 + 1;
println!("{count}");
}
When both operands are constants, the lint arithmetic_overflow denies the program at compile time.
fn order_fits(price: i32, quantity: i32, budget: i32) -> bool {
match price.checked_mul(quantity) {
Some(total) => total <= budget,
None => false, // the total does not fit in an i32
}
}
fn main() {
println!("3 items: {}", order_fits(100, 3, 1000));
println!("42949673 items: {}", order_fits(100, 42949673, 1000));
println!("wrapping: {}", 100i32.wrapping_mul(42949673));
}
3 items: true
42949673 items: false
wrapping: 4
- Verdict: native. A debug build panics on overflow, and the Rust reference calls overflow a programmer error, not undefined behavior.
- A release build wraps unless the profile sets
overflow-checks = true. Do not rely on the debug check to protect a release. checked_*methods returnNoneon overflow in every build.wrapping_*,overflowing_*andsaturating_*state the other intents in the code.- A conversion with
astruncates silently.i32::try_from(value)returns an error when the value does not fit.
References
- CWE-190: Integer Overflow or Wraparound, Description; Extended Description; Alternate Terms; Common Consequences; Potential Mitigations; Relationships; Observed Examples
- 2025 CWE Top 25, Weaknesses On the Cusp, the ranked list, rank 30, CVEs in KEV, Rank Last Year
- OWASP Top 10:2025, Next Steps, X02:2025 Memory Management Failures, X02:2025, Description; How to prevent; List of Mapped CWEs
- blexim, Basic Integer Overflows, Phrack Magazine 11(60), article 10, December 2002, 1.2 What is an integer overflow?; 1.3 Why can they be dangerous?
- Clang documentation, UndefinedBehaviorSanitizer, Available checks, -fsanitize=signed-integer-overflow and -fsanitize=unsigned-integer-overflow
- cppreference, ckd_add, the description and the return value
- The Rust Programming Language, Data Types, Integer Overflow
- The Rust Reference, Behavior not considered unsafe, Integer overflow
- The Go Programming Language Specification, Integer overflow
- Java SE 25 API, java.lang.Math, addExact; multiplyExact
- C# language reference, The checked and unchecked statements, the opening section
- The Python Standard Library, Built-in Types, Numeric Types, int, float, complex
- The Python Standard Library, ctypes, Fundamental data types, c_byte and the other integer types
- MDN Web Docs, Number.MAX_SAFE_INTEGER, Description
- CodeQL query help, Uncontrolled data in arithmetic expression (cpp/uncontrolled-arithmetic), the query description; Recommendation
- CodeQL query help, Multiplication result converted to larger type (cpp/integer-multiplication-cast-to-long), the query description
- CVE-2002-0639, OpenSSH, the description and the publication date
- CVE-2021-30860, Apple CoreGraphics, the description and the publication date
- CVE-2025-27363, FreeType, the description and the publication date
- The Java Language Specification, Java SE 25 Edition, 15.17.1 Multiplication Operator *
- Kotlin documentation, Numbers, Data overflow, Overflow in operations
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag PQW5JT Edit this page History Report an error Markdown