rust - 什么是导致段错误的 Rust 代码示例?
问题描述
我在 Rust 中搜索了一些段错误示例,但现在没有崩溃。Rust 现在能防止所有的段错误吗?是否有可能导致段错误的简单演示?
解决方案
如果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 如何保证它不会发生。
如果可以避免,请不要使用不安全的代码。
推荐阅读
- sql - 跨行选择具有多个条件的行
- c# - 在dragablz的所有其他选项卡中显示的另一个选项卡中具有相似长度的文本框的虚线:TabablzControl wpf mvvm
- angularjs - 登录 ionic 5 后更新侧边菜单
- javascript - graphqlHTTP 不是函数
- azure - Github 身份提供程序未出现在登录对话框中
- pandoc - 转换为 HTML 时为复选框编写 Ascii
- malware - 如何故意触发病毒扫描的误报?
- javascript - 我的浏览器不断抛出错误,提示“未捕获的 TypeError:n.charAt 不是函数”
- sql - 如何使用 sql server 查询获取这些数据?
- swiftui - SwiftUI 侧边栏不记得状态