FAQ - Help and questions

What happens on integer overflow in Rust, and which operation should I use?

#security#integers#overflowpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

With the plain operators, overflow panics in debug builds and wraps silently in release builds unless overflow-checks is on. Choose the behaviour explicitly: checked_ returns None, saturating_ clamps, wrapping_ wraps on purpose. For sizes and amounts that come from outside, use checked.

Checked with rustc 1.93.0, Windows 11 (the same program built in debug and in release)

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

The Rust Book states the rule: when compiling in debug mode, Rust includes checks for integer overflow that cause the program to panic; in release mode, it does not include them, and overflow wraps around in two's complement. That is memory safe, but a wrapped size or amount is a logic bug that can turn into a security bug (a length that wrapped to a small number, a balance that became negative or huge).

The program uses black_box so the compiler cannot compute the sums at compile time and reject them.

src/main.rsrust
use std::hint::black_box;

fn main() {
    let a: u8 = black_box(250);
    let b: u8 = black_box(10);

    println!("checked:    {:?}", a.checked_add(b));
    println!("wrapping:   {}", a.wrapping_add(b));
    println!("saturating: {}", a.saturating_add(b));
    println!("overflowing: {:?}", a.overflowing_add(b));

    // The plain operator: the behaviour depends on the build profile.
    let plain = a + b;
    println!("plain a + b: {plain}");
}

Built in release mode (cargo run --release):

text
checked:    None
wrapping:   4
saturating: 255
overflowing: (4, true)
plain a + b: 4

Built in debug mode (cargo run), the same program stops at the plain operator:

text
checked:    None
wrapping:   4
saturating: 255
overflowing: (4, true)
thread 'main' panicked at src\bin\b29.rs:13:17:
attempt to add with overflow
MethodOn overflowUse for
checked_addNoneAnything from outside: lengths, counts, amounts
saturating_addstays at the maximum or minimumCounters and limits where clamping is right
wrapping_addwraps, on purposeHashes, checksums, ring buffers
overflowing_addresult and a flagWhen you need both

How to do it#

  1. Use checked_ operations on every arithmetic step that involves untrusted numbers, and turn None into an error.
  2. Convert between integer types with try_from, not as; as silently truncates.
  3. Test with large values, not just typical ones.
  4. If a release build must also fail on overflow, set overflow-checks = true in [profile.release] of Cargo.toml. It costs some speed; measure it for your program.

Common mistakes#

  • Testing only in debug mode and assuming release behaves the same.
  • Using as to shrink a u64 into a u32 or usize.
  • Adding a user-supplied length to an offset before comparing with a limit; compare first (see the thread on length fields).

Does overflow checking apply to unsafe code?#

The arithmetic rules are the same. Where a wrong size feeds an unchecked operation, an overflow can turn into memory corruption, which is a reason to keep size computations checked.

Should I enable overflow-checks in release?#

For services handling money, sizes or counters from outside, many teams do. Measure the cost for your program; the explicit checked_ methods remain the clearest way to express intent.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet