Sub topic 9
Integer overflow in debug and release builds
This chapter assumes you know Rust's integer types (u8, i32, usize and so on), can run a program with cargo run, and can read a panic message. It covers what happens when arithmetic produces a value that does not fit in the type, why the answer depends on the build profile, and which tools make the behavior explicit.
What overflow is
Every fixed-size integer type has a range. A u8 holds 0 to 255. An i8 holds -128 to 127. Integer overflow happens when an arithmetic operation produces a result outside that range, such as 250u8 + 10 or 0u8 - 1.
Rust does not leave this undefined, as C does for signed overflow. Rust defines exactly two outcomes for the plain operators +, -, * and similar:
- A panic, which stops the thread with an error message.
- Wrapping, where the result is reduced modulo 2^N for an N-bit type (two's complement wraparound).
Which of the two you get depends on whether overflow checks are enabled in the current build.
Debug versus release behavior
By default, cargo build and cargo run use the dev profile, which has overflow checks on. cargo build --release uses the release profile, which has them off. The same source can therefore behave differently:
fn add(a: u8, b: u8) -> u8 {
a + b
}
fn main() {
let result = add(250, 10);
println!("result = {result}");
}| Build | Command | Outcome |
|---|---|---|
| Debug | `cargo run` | Panics with `attempt to add with overflow` |
| Release | `cargo run --release` | Prints `result = 4` |
In the release build, 250 + 10 = 260, and 260 - 256 = 4. The program keeps running with a wrong value. This is the main risk of the default: a bug that panics loudly during development can pass silently in production.
Changing the default with a profile setting
The behavior is controlled by the overflow-checks setting. You can change it per profile in Cargo.toml:
[package]
name = "overflow-demo"
version = "0.1.0"
edition = "2021"
[profile.release]
overflow-checks = trueWith this setting, release builds also panic on overflow. You pay a small runtime cost for each checked operation. Many teams turn this on for services where a silent wrong number is worse than a crash, such as billing or accounting code. You can also set overflow-checks = false in the dev profile, but that hides bugs during development and is rarely a good idea.
Compile-time detection
The compiler also catches some overflows before the program runs. When it can see all operands as constants, it reports an error in every profile:
fn main() {
let x: u8 = 255;
let y = x + 1; // error: this arithmetic operation will overflow
println!("{y}");
}This check is a deny-by-default lint named arithmetic_overflow. It only fires when the compiler can prove the overflow from constants, which is why the earlier example put the addition inside a function with parameters. A literal that is too big for its type is rejected by a related lint, overflowing_literals. For example, let n: u8 = 256; does not compile.
Do not depend on these lints for safety. They catch obvious mistakes, not overflow caused by runtime data.
The four explicit families
For each arithmetic operation, the integer types provide four method families. Each one states what should happen on overflow and behaves the same in debug and release builds. Using 100i8 plus 100i8 as the example (the true result, 200, does not fit in i8):
| Method | Return type | Result for `100i8 + 100` |
|---|---|---|
| `checked_add` | `Option<i8>` | `None` |
| `wrapping_add` | `i8` | `-56` |
| `overflowing_add` | `(i8, bool)` | `(-56, true)` |
| `saturating_add` | `i8` | `127` |
The same prefixes exist for sub, mul, div, neg, pow, abs, shl, shr and others, though not every family exists for every operation. This code runs all four:
fn main() {
let a: i8 = 100;
let b: i8 = 100;
println!("{:?}", a.checked_add(b));
println!("{}", a.wrapping_add(b));
println!("{:?}", a.overflowing_add(b));
println!("{}", a.saturating_add(b));
}It prints:
None
-56
(-56, true)
127checked: treat overflow as a recoverable error
checked_* returns None when the operation overflows. Use it when overflow means the input or state is invalid and the caller should decide what to do. It combines well with iterator methods such as try_fold:
fn sum_checked(values: &[u32]) -> Option<u32> {
values.iter().try_fold(0u32, |acc, &v| acc.checked_add(v))
}
fn main() {
println!("{:?}", sum_checked(&[1, 2, 3]));
println!("{:?}", sum_checked(&[u32::MAX, 1]));
}The first call prints Some(6) and the second prints None. try_fold stops at the first None, so the function reports failure without needing a flag variable.
wrapping: modular arithmetic on purpose
wrapping_* is the right choice when wraparound is the intended math. Hash functions, checksums, pseudo-random number generators, and sequence numbers in network protocols all work modulo a power of two. This is the 32-bit FNV-1a hash:
fn fnv1a(data: &[u8]) -> u32 {
let mut hash: u32 = 0x811c9dc5;
for &byte in data {
hash ^= u32::from(byte);
hash = hash.wrapping_mul(0x0100_0193);
}
hash
}
fn main() {
println!("{:08x}", fnv1a(b"hello"));
}With a plain *, this function would panic in debug builds as soon as the hash grows past u32::MAX. With wrapping_mul, it gives the same result in every build.
saturating: clamp at the limit
saturating_* stops at MAX or MIN instead of wrapping. It suits values that represent a quantity and should not flip sign or jump to a small number, such as a volume level, a pixel brightness, or a countdown that should stop at zero.
fn main() {
let brightness: u8 = 240;
println!("{}", brightness.saturating_add(50));
let remaining: u32 = 3;
println!("{}", remaining.saturating_sub(10));
}This prints 255 and then 0.
overflowing: keep both the value and the flag
overflowing_* returns the wrapped value and a bool telling you whether overflow happened. It is the right tool for multi-word arithmetic, where you must carry the overflow into the next word, and for cases where you want to compute the wrapped value but also log or count the event.
Wrapper types for whole expressions
If most of a block of code should wrap, calling wrapping_add on every operator is noisy. The standard library provides std::num::Wrapping<T> and std::num::Saturating<T>. They are wrapper types whose operators always wrap or saturate:
use std::num::Wrapping;
fn main() {
let a = Wrapping(250u8);
let b = Wrapping(10u8);
println!("{}", a + b);
let mut counter = Wrapping(u8::MAX);
counter += 1;
println!("{}", counter);
}This prints 4 and then 0, in both debug and release builds. The cost is that you must wrap values on the way in and unwrap them with .0 on the way out.
Common places overflow surprises people
Unsigned subtraction
Subtracting from an unsigned type goes below zero easily, and usize is the most common victim because lengths and indexes use it:
fn last_index(len: usize) -> usize {
len - 1
}
fn main() {
println!("{}", last_index(3));
println!("{}", last_index(0));
}The first call prints 2. The second panics in debug builds. In release builds it returns usize::MAX, a huge index. The fix is to say what an empty input means:
fn last_index(len: usize) -> Option<usize> {
len.checked_sub(1)
}
fn main() {
println!("{:?}", last_index(3));
println!("{:?}", last_index(0));
}This prints Some(2) and then None.
Operations that panic regardless of profile
Some operations are checked in all builds, because they have no sensible wrapped result:
- Division or remainder by zero always panics.
i32::MIN / -1always panics, because the true result, 2147483648, does not fit ini32.abs()onMIN(for examplei32::MIN.abs()) overflows. It panics in debug builds and wraps back toMINin release builds. Usechecked_absorunsigned_absinstead.- Shifting by an amount equal to or larger than the bit width, such as
1u32 << 32, panics in debug builds. Usechecked_shlorwrapping_shlwhen the shift amount comes from data.
`as` casts never panic
A cast with as is not arithmetic, so overflow checks do not apply to it. 300i32 as u8 silently gives 44 in both debug and release builds. If you want a failure when the value does not fit, use u8::try_from(300i32), which returns an Err. Chapter material on conversions covers this in more detail.
Choosing an approach
- If overflow means bad input or a logic error that the caller should handle, use
checked_*and return anOptionorResult. - If the algorithm is defined modulo 2^N, use
wrapping_*orWrapping<T>. - If the value is a clamped quantity, use
saturating_*. - If you need the wrapped value and the overflow flag together, use
overflowing_*. - If overflow would be a bug and you want to find it, keep the plain operators and enable
overflow-checksin the release profile when the performance cost is acceptable. - Test with both
cargo testandcargo test --releaseif your code does arithmetic near the type limits, since the two profiles can disagree.
Exercise
The function fn double(x: u8) -> u8 { x * 2 } is called as double(200). What happens under cargo run and under cargo run --release, and how would you rewrite the function so it returns None instead of either result?
Show answer
Under cargo run (debug) the multiplication overflows because 400 does not fit in a u8, so the program panics with "attempt to multiply with overflow". Under cargo run --release, overflow checks are off, so the result wraps to 400 - 256 = 144 and the program continues. To return None in both builds, write fn double(x: u8) -> Option<u8> { x.checked_mul(2) }. Then double(200) returns None and double(100) returns Some(200).
Exercise
A volume control stores the level in a u8 from 0 to 255. Write a function adjust(level: u8, delta: i16) -> u8 that adds a signed delta and clamps the result to the range 0 to 255 without ever panicking or wrapping.
Show answer
Widen to i16, add, and clamp before narrowing: fn adjust(level: u8, delta: i16) -> u8 { (i16::from(level) + delta).clamp(0, 255) as u8 }. This cannot overflow, because i16 easily holds any sum of a u8 and the delta in the intended range, and a plain as u8 is safe after the clamp since the value is already between 0 and 255. For example, adjust(240, 50) returns 255 and adjust(10, -50) returns 0. A caller who passes a delta near i16::MAX or i16::MIN could still overflow the i16 addition, so use i16::from(level).saturating_add(delta) before clamping if the delta can be extreme.