rust-lang / rust-clippy

A bunch of lints to catch common mistakes and improve your Rust code. Book: https://doc.rust-lang.org/clippy/
https://rust-lang.github.io/rust-clippy/
Other
11.24k stars 1.51k forks source link

lint for integer overflow, especially in release mode #12503

Open bingmatv opened 5 months ago

bingmatv commented 5 months ago

What it does

Rust panics for integer overflow in debug mode, but it will wrap around any integers in release mode, aka, when --release parameter is added for cargo.

Advantage

No response

Drawbacks

No response

Example

fn main() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let s = (s.trim().parse::<u8>().unwrap()) * 3;
}

It accepts user input then multiply the accepted integer by 3, may wrap around when multiply by 3.

taiki-e commented 5 months ago

This seems to be covered by arithmetic_side_effects?

bingmatv commented 5 months ago

This seems to be covered by arithmetic_side_effects?

cargo clippy only showed: warning: unused variable: s --> src/main.rs:4:9 | 4 | let s = (s.trim().parse::().unwrap()) * 3; | ^ help: if this is intentional, prefix it with an underscore: _s Only warned about unused variable.

taiki-e commented 5 months ago

arithmetic_side_effects is in the restriction lint group, which is allowed by default, so you have to explicitly enable it.

#![warn(clippy::arithmetic_side_effects)] // <-------------
#![allow(dead_code, unused_variables)]

fn main() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let s = (s.trim().parse::<u8>().unwrap()) * 3;
}
warning: arithmetic operation that can potentially result in unexpected side-effects
 --> src/main.rs:7:13
  |
7 |     let s = (s.trim().parse::<u8>().unwrap()) * 3;
  |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#arithmetic_side_effects
note: the lint level is defined here
 --> src/main.rs:1:9
  |
1 | #![warn(clippy::arithmetic_side_effects)]
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

playground

ijackson commented 5 months ago

Unfortunately arithmetic_side_effects is quite poor:

But probably it doesn't make sense to use this ticket as a tracking issue for problems with this lint; it shoud be closed.