Skip to content

fix(unsafe): use unchecked_add in may_overflow to accurately model UB - #3275

Open
Aditya-9-6 wants to merge 2 commits into
google:mainfrom
Aditya-9-6:fix/may-overflow-ub-unchecked-add
Open

fix(unsafe): use unchecked_add in may_overflow to accurately model UB#3275
Aditya-9-6 wants to merge 2 commits into
google:mainfrom
Aditya-9-6:fix/may-overflow-ub-unchecked-add

Conversation

@Aditya-9-6

Copy link
Copy Markdown

Summary

Updates the may_overflow example in the Unsafe Deep Dive chapter to use i32::unchecked_add instead of standard +.

Background

In standard Rust, integer overflow (a + i32::MAX) is not undefined behavior: it panics with overflow checks enabled (debug mode) and performs two's-complement wrapping in release mode.

Using unchecked_add:

  1. Genuinely justifies the unsafe function signature and block.
  2. In debug builds, it triggers the standard library's precondition panic:
    unsafe precondition(s) violated: i32::unchecked_add cannot overflow
    
  3. In release builds, it produces actual Undefined Behavior (UB) as the slide intends to teach.

The speaker notes have been updated accordingly to clarify the distinction between safe Rust arithmetic (which wraps in release mode) and unchecked operations (which produce UB).

Fixes #3122
Relates #3021

@google-cla

google-cla Bot commented Sep 4, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unsafe Rust: Integer overflow is not UB

1 participant