In Rust, what happens when a ledger's `u8` pending-transfer counter at 255 is incremented, in a debug build and in a release build?
answer
- two build modes, two outcomes
- a panic message naming the operator
- two's complement in release
- debug assertions switch the check on
basics
~20 sA debug build panics with "attempt to add with overflow"; a default release build silently wraps the counter to 0. Neither is undefined behaviour, and code that means to wrap or stop must say so explicitly.
solid answer
~40 sRust integers have fixed widths, so a `u8` holds 0 to 255 and `255 + 1` has no answer in the type. In a debug build (and under `cargo test`) rustc inserts an overflow check, and the program panics with `attempt to add with overflow`. A default release build omits the check and wraps in two's complement, so the counter becomes 0 and keeps counting from there. The Reference treats any overflow as a programmer error but never as undefined behaviour. Constant overflow such as `let x: u8 = 255 + 1;` is rejected at compile time by the deny-by-default `arithmetic_overflow` lint. If wrapping is the intent, write `wrapping_add`; if overflow is a bug or bad input, use `checked_add` or a wider type.
code
rust · 11 linesfn add_pending(pending: u8) -> u8 {
pending + 1
}
fn main() {
let mut pending: u8 = 250;
for _ in 0..10 {
pending = add_pending(pending);
}
println!("pending = {pending}");
}go deeper
Recall the integer widths, the i32 and f64 literal defaults, and the two outcomes: a debug build panics with attempt to add with overflow, a release build wraps.
Explain that the check is compiled in with debug assertions, that tests run with it, and that the methods checked_add, wrapping_add and saturating_add state intent in every build.
Show why tests in debug miss release-only corruption: an unseen input wraps silently in production, so overflow-prone paths need explicit methods rather than reliance on the build profile.
Frame the profile default as a speed-for-safety trade a team can revisit, and decide where a wrong number is worse than a panic or an error.
## Fixed-width integers Rust has no arbitrary-size integer in the language. Every integer type has a **fixed width** that is part of its name: | Signed | Unsigned | Width | |---|---|---| | `i8` | `u8` | 8 bits | | `i16` | `u16` | 16 bits | | `i32` | `u32` | 32 bits | | `i64` | `u64` | 64 bits | | `i128` | `u128` | 128 bits | | `isize` | `usize` | the platform's pointer width | Signed types use **two's complement**, so `i8` runs from -128 to 127 and `u8` from 0 to 255. `usize` is what slices and `Vec` are indexed by: `v[i]` with `i: u32` fails with E0277 ("the type `[{integer}]` cannot be indexed by `u32`"). The Reference only guarantees that `usize` is at least 16 bits wide, so never assume it is 64. When nothing else constrains a literal, the compiler picks a **default**: - `let n = 7;` is an `i32`. - `let x = 2.5;` is an `f64`. - A suffix or an annotation overrides it: `7u8`, `2.5f32`, `let n: u64 = 7;`. ## What happens at 255 + 1 **Integer overflow** is an arithmetic result that does not fit the type. For a `u8` counter at 255, adding 1 overflows. What happens depends on the build: 1. **Debug build** (`cargo build`, `cargo run`, `cargo test`): rustc compiles in an **overflow check** and the program panics. The message names the operation: `attempt to add with overflow` (or `subtract`, `multiply`, `negate`). 2. **Release build** (`cargo build --release`) with the default profile: the check is left out and the value **wraps** in two's complement. `255u8 + 1` becomes 0, and 250 plus ten increments becomes 4. The Reference states the contract precisely: overflow is always a programmer error; when debug assertions are on, implementations must panic; in other builds they may panic or wrap, and if they wrap the result must follow two's complement. So overflow in safe Rust is **never undefined behaviour**, unlike signed overflow in C, but a release binary may quietly carry a wrong number forward. The switch behind this is a codegen option tied to the build profile; Cargo's profiles material covers the `overflow-checks` key that controls it. ## What the compiler catches before run time Some overflow never reaches the binary: - `let x: u8 = 256;` fails with `literal out of range for u8` (the deny-by-default `overflowing_literals` lint). - `let x: u8 = 255 + 1;` fails with `this arithmetic operation will overflow` (the deny-by-default `arithmetic_overflow` lint), because the compiler can evaluate the constant expression. A value that only exists at run time, such as a counter loaded from storage or a function argument, cannot be checked this way, which is why the runtime check exists at all. ## Saying what you mean The integer types carry explicit methods, so the code states the policy instead of the build profile choosing it: - `pending.checked_add(1)` returns `Option<u8>`, `None` on overflow. - `pending.wrapping_add(1)` wraps on purpose, in every build. - `pending.saturating_add(1)` stops at 255. - A wider type (`u16`, `u32`) is the right fix when 255 was simply too small. For a ledger counter, wrapping to 0 is a silent data error, so the honest options are a wider type or `checked_add` with an error path. ## Choosing a width in the first place Most overflow bugs start as a width chosen for convenience. A few working rules: - **Counts and amounts that grow with traffic** (pending transfers, token balances, byte totals) get `u32` or `u64`; a `u8` saves three bytes and buys a bug. - **Lengths and indexes** are `usize`, because that is what `len()` returns and what indexing accepts; converting back and forth invites casts. - **Signed deltas** (refunds, adjustments) need a signed type such as `i64`; subtracting two `u64` values that may go below zero overflows instead of going negative. - **`i128` and `u128`** exist for intermediate products, such as multiplying an amount by a rate, where a 64-bit result could overflow before the division brings it back down. - **Small types** (`u8`, `i16`) earn their place when the domain is genuinely bounded, such as a byte, a percentage or a protocol field, or when millions of them sit in memory. ## Why the split exists The checks cost a compare and a branch on every arithmetic operation. Debug builds pay that to catch bugs in development and in tests; release builds drop it by default for speed. The consequence for interviews is simple: **a test suite run in debug catches overflow that the shipped release binary would wrap silently**, so an input that never appeared in tests can still corrupt a release build's state.
- Why does `let x: u8 = 255 + 1;` fail to compile when passing 255 to a function that adds 1 only fails at run time?The compiler can evaluate `255 + 1` as a constant, and the deny-by-default `arithmetic_overflow` lint rejects it with "this arithmetic operation will overflow". Inside a function, the argument is unknown until run time, so only the runtime overflow check (debug) or wrapping (release) applies. A literal that is itself too big, like `256` for a `u8`, trips `overflowing_literals` instead.
- Does `cargo test` catch an overflow that a release binary would wrap?Yes. Cargo's test profile inherits from the dev profile, which keeps overflow checks on, so the test panics with `attempt to add with overflow` and fails. The danger is the input no test exercised: the release build then wraps silently instead of failing loudly.
- Why does `v[i]` fail to compile when `i` is a `u32`?Slices and `Vec` are indexed only by `usize` (or ranges of `usize`), the pointer-width unsigned type, so rustc reports E0277: the type cannot be indexed by `u32`. Declare the index as `usize`, or convert at the boundary where you know the value fits.
A car's mechanical odometer that rolls from 999999 back to 000000 is release-mode wrapping; a dashboard that stops the car and flashes an error at the rollover is the debug build's panic.
- Integer overflow in safe Rust is undefined behaviour, just as in C.
- Release builds panic on overflow by default, exactly like debug builds.
- Rust promotes a u8 to a wider type automatically when it overflows.
- The compiler catches every overflow at compile time.
- An unannotated integer literal defaults to i64 on a 64-bit machine.
- usize is always 64 bits wide.