Sub topic 9
Integer overflow in debug and release builds
This chapter assumes you can build and run a Rust program with cargo, and that you know the fixed-width integer types such as u8 and i32 from the previous chapters.
What overflow is
Every integer type has a fixed range. A u8 holds 0 to 255. An i8 holds -128 to 127. Overflow happens when an arithmetic result falls outside the range of its type, for example 250u8 + 10, which would be 260.
Rust does not leave this case undefined. What it does depends on the build profile.
Debug builds versus release builds
| Build | Command | Behavior on `+`, `-`, `*` overflow |
|---|---|---|
| Debug | `cargo build`, `cargo run` | Panics with "attempt to add with overflow" |
| Release | `cargo build --release` | Wraps around in two's complement, with no panic |
In a debug build the compiler inserts overflow checks. In a release build those checks are off by default for speed, so 255u8 + 1 becomes 0. Wrapping in release is defined behavior, not a memory-safety problem. It is still almost always a logic bug.
You can change the default with the overflow-checks setting in Cargo.toml:
[profile.release]
overflow-checks = trueThe compiler also rejects overflow it can see at compile time. A line such as let x: u8 = 255 + 1; fails with an error from the arithmetic_overflow lint, in every profile.
Four explicit methods
Integer types provide four families of methods that make the overflow behavior part of the code. The same result then appears in debug and release builds.
fn main() {
let a: u8 = 250;
println!("{:?}", a.checked_add(10));
println!("{}", a.wrapping_add(10));
println!("{:?}", a.overflowing_add(10));
println!("{}", a.saturating_add(10));
}This prints:
None
4
(4, true)
255Each method handles 250 + 10 differently:
checked_addreturns anOption. You getSome(result)if the value fits andNoneif it overflowed.wrapping_addalways wraps around. 260 minus 256 is 4.overflowing_addreturns a tuple of the wrapped value and aboolthat says whether overflow happened.saturating_addclamps the result at the type's minimum or maximum, here 255.
The same four prefixes exist for subtraction, multiplication, and other operations, such as checked_sub, wrapping_mul, and saturating_sub.
Choosing a method
| You want | Use |
|---|---|
| To treat overflow as an error you must handle | `checked_*` |
| Modular arithmetic, such as hashes or counters that roll over | `wrapping_*` |
| A value that stops at the limit, such as a volume or a health bar | `saturating_*` |
| The wrapped value and to know whether it wrapped | `overflowing_*` |
A common pattern combines checked_* with match or ok_or:
fn add_items(current: u32, extra: u32) -> Result<u32, String> {
current
.checked_add(extra)
.ok_or_else(|| format!("overflow adding {extra} to {current}"))
}
fn main() {
println!("{:?}", add_items(10, 5));
println!("{:?}", add_items(u32::MAX, 1));
}The first call prints Ok(15). The second prints Err("overflow adding 1 to 4294967295").
Overflow elsewhere
Addition, subtraction, and multiplication are not the only operations that can overflow. Negating i32::MIN overflows, because +2,147,483,648 does not fit in an i32. So does i32::MIN / -1. Shifting by an amount greater than or equal to the bit width also fails the check in debug builds. Casting with as never panics. It truncates silently, as the conversions chapter covers.
Instead of a diagram of internals, use this decision flow when you write arithmetic.
Common mistakes
- Relying on the debug panic as error handling. It is absent in release builds by default.
- Using
wrapping_*to silence a panic without deciding that wrapping is correct. - Picking a type that is too small, such as
u8for a running total. Choosingu64often removes the problem. - Subtracting unsigned values, such as
len - 1whenlenis0usize. This is the most frequent overflow in real code. Usechecked_suborsaturating_sub.
Exercise
What does 200u8.saturating_add(100) return, and what would 200u8.wrapping_add(100) return?
Show answer
saturating_add returns 255, the maximum for u8. wrapping_add returns 44, because 300 minus 256 is 44.
Exercise
A release build of your program prints 0 for let n: u8 = 255; n + 1 computed at run time, but the same code panics under cargo run. Why, and how do you make both builds agree?
Show answer
Debug builds enable overflow checks and panic. Release builds disable them by default and wrap. To make both agree, use an explicit method such as checked_add and handle the None case, or set overflow-checks = true in the release profile.