【发布时间】:2021-03-10 05:31:28
【问题描述】:
我的静态库 crate 中有这样的函数:
use super::*;
static BLANK_VEC: [u8; 16] = [0_u8; 16];
pub fn pad(name: &'static str) -> String {
let mut res = String::from(name);
res.push_str(&String::from_utf8_lossy(&BLANK_VEC[name.len()..]));
res
}
当我将它链接到 C 代码时,它按预期工作,但如果我链接下面的代码(唯一的区别是 const 而不是 static)标签 BLANK_VEC 不会出现在 ELF 文件中.它可以编译并运行,直到它得到一个 HardFault。
use super::*;
const BLANK_VEC: [u8; 16] = [0_u8; 16];
pub fn pad(name: &'static str) -> String {
let mut res = String::from(name);
res.push_str(&String::from_utf8_lossy(&BLANK_VEC[name.len()..]));
res
}
这是 Rust 方面的错误吗?我这么认为是因为const 变量不知何故超出了范围。我可以引用它并编译它。内存安全保障在哪里?为什么我不必使用 unsafe 块来执行此操作?
如果这取决于我的链接器:我使用arm-gcc-none-eabi。
编辑:我理解为什么会发生这种情况,但 Rust 不应该确保用户使用不会消失的变量吗?
【问题讨论】:
-
另见stackoverflow.com/a/52753798/1021920,尤其是“发生次数”下方的文字
-
stackoverflow.com/questions/52751597/… 和 stackoverflow.com/questions/45550387/… 尤其是
const and static do not mean the same things in Rust and C部分 -
既然问题已经发布了一个很好的答案,我认为最好把这个问题留作为什么符号
BLANK_VEC没有出现在链接器输出中 (这就是 Masklinn 的回答)并针对 为什么我在运行此代码时出现错误 提出一个新问题(您还应该为此提供更多上下文,例如您链接到的 C 代码)。在答案已经发布后更改问题是不受欢迎的;提出一个新问题很好,也值得鼓励。 -
好的会这样做
标签: c memory-management rust linker