Rust安全之数值

文章目录

数值溢出

编译通过,运行失败

cargo run 1

rust 复制代码
fn main() {
    let mut arg = std::env::args()
        .skip(1)
        .map(|x| x.parse::<i32>().unwrap())
        .next()
        .unwrap();
    let m_i = i32::MAX - 1;
    let a = m_i + arg;

    println!("{:?}", a);
}
bash 复制代码
thread 'main' panicked at 'attempt to add with overflow', src\bin\rssh3.rs:13:13
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
error: process didn't exit successfully: `target\debug\rssh3.exe 1` (exit code: 101)

编译不通过

rust 复制代码
fn main() {
    let m_i = i32::MAX;
    let a = m_i + 1;

    println!("{:?}", a);
}

输出

bash 复制代码
error: this arithmetic operation will overflow
 --> src\bin\rssh3.rs:9:13
  |
9 |     let a = m_i + 1;
  |             ^^^^^^^ attempt to compute `i32::MAX + 1_i32`, which would overflow
  |
  = note: `#[deny(arithmetic_overflow)]` on by default

warning: `datetime-util` (bin "rssh3") generated 4 warnings
error: could not compile `datetime-util` due to previous error; 4 warnings emitted
相关推荐
神奇小汤圆3 分钟前
Kafka性能调优:从10万到100万条/秒的实战经验
后端
ylscode7 分钟前
黑客利用 GHOSTYNETWORKS 和 OMEGATECH 托管 JS 恶意软件基础设施
开发语言·安全·php·安全威胁分析
爱吃生蚝的于勒8 分钟前
QT开发第二章——信号和槽
c语言·开发语言·c++·qt
xcLeigh13 分钟前
Python入门:Python3 operator模块全面学习教程
开发语言·python·学习·教程·python3·operator
Gopher_HBo14 分钟前
接入层LVS
后端
404号扳手14 分钟前
Java 基础知识(六)
java·后端
大叔带刺15 分钟前
使用python创建自己的专属星座签名APP:Name2Constell
开发语言·python·pygame
z落落17 分钟前
C# 类与对象、字段、静态与非静态+四大访问修饰符
开发语言·c#
思麟呀21 分钟前
C++工业级日志项目(八)最终上层接口
开发语言·c++
前端市界23 分钟前
LotDB Vue 阿里云 ECS 部署实战记录
后端