在安全的 Rust 中是否可能出现未定义的行为? [英] Is undefined behavior possible in safe Rust?

查看:46
本文介绍了在安全的 Rust 中是否可能出现未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在不使用 unsafe 的情况下在 Rust 中实现未定义的行为?

当然,这样的行为可以被第三方库包装在一个安全"的文件中.函数,所以假设我们只使用标准函数.

解决方案

绝对可以,但是 任何此类情况都是 Rust 或标准库的错误.

我最喜欢的例子是LLVM 循环优化可以使安全程序崩溃,这实际上是由于 Rust 和 LLVM 语义的不良交互而发生的:

pub fn oops() {(|| 循环 {掉落(42)})()}

在 Rust 1.49.0 上进行优化编译,生成程序集:

playground::oops:UD2

<块引用>

这样的行为可以被第三方库包装在一个安全"的文件中.函数所以让我们假设我们只使用标准的

标准库一个第三方库",所以我没有区别.

Is there any way to achieve undefined behavior in Rust without using unsafe?

Of course, such behavior can be wrapped by a third-party library in a "safe" function so let's assume we're using only the standard one.

解决方案

Absolutely, but any such case is a bug with Rust or the standard libary.

My favorite example is LLVM loop optimization can make safe programs crash, which actually occurs due to a poor interaction of Rust and LLVM semantics:

pub fn oops() {
    (|| loop {
        drop(42)
    })()
}

Compiled with optimizations on Rust 1.49.0, this produces the assembly:

playground::oops:
    ud2

such behavior can be wrapped by a third-party library in a "safe" function so let's assume we're using only the standard one

The standard library is a "third-party library", so I don't get the distinction.

这篇关于在安全的 Rust 中是否可能出现未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆