首页 > 解决方案 > 什么是导致段错误的 Rust 代码示例?

问题描述

我在 Rust 中搜索了一些段错误示例,但现在没有崩溃。Rust 现在能防止所有的段错误吗?是否有可能导致段错误的简单演示?

标签: rustsegmentation-fault

解决方案


如果unsafe允许代码,则:

fn main() {
    unsafe { std::ptr::null_mut::<i32>().write(42) };
}

结果是:

   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 1.37s
     Running `target/debug/playground`
timeout: the monitored command dumped core
/playground/tools/entrypoint.sh: line 11:     7 Segmentation fault      timeout --signal=KILL ${timeout} "$@"

正如在操场上看到的那样。


任何会触发段错误的情况都需要在某个时候调用未定义的行为。允许编译器优化代码或以其他方式利用不应该发生未定义行为的事实,因此很难保证某些代码会出现段错误。编译器完全有权在不触发段错误的情况下运行上述程序。

例如,上面的代码在发布模式下编译时会导致“非法指令”。


如果unsafe不允许使用代码,请参阅Rust 如何保证内存安全并防止段错误?只要不违反其内存安全不变量(这只能在unsafe代码中发生),Rust 如何保证它不会发生。

如果可以避免,请不要使用不安全的代码。


推荐阅读