Skip to content

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

Merged
fw-immunant merged 3 commits into
google:mainfrom
Aditya-9-6:fix/may-overflow-ub-unchecked-add
Sep 11, 2026
Merged

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

Conversation

@Aditya-9-6

Copy link
Copy Markdown
Contributor

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.

@fw-immunant fw-immunant left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, this corrects the factual error and explains the situation clearly. Thanks!

I think we should merge this as a conservative correctness fix, but it's worth noting that there is another open PR (#3244) addressing the same issue in a different way (by changing to an unrelated example with a safety contract around indexing). But that PR is not yet ready to merge and is a more substantial alteration to the curriculum, so I'd rather merge this now and later decide whether #3244 should merge at all and if so in what form.

@fw-immunant
fw-immunant merged commit 8273299 into google:main Sep 11, 2026
44 checks passed
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

2 participants