我试图从指针中读取一个值,但是我总是得到一个double-free错误。你们知道怎么解决吗?我使用mem::forget来阻止空闲操作,但仍然得到了相同的结果。
use std::ptr;
use std::mem;
fn main() {
let test = String::from("hello!");
println!("{}", get_value_from_ptr(&test));
println!("{}", get_value_from_ptr(&test));
}
fn get_value_from_ptr<T>(val: &T) -> T {
let value = unsafe { ptr::read(val) };
mem::forget(&value);
value
}错误:
Compiling playground v0.0.1 (/playground)
Finished dev [unoptimized + debuginfo] target(s) in 1.26s
Running `target/debug/playground`
free(): double free detected in tcache 2
timeout: the monitored command dumped core
/playground/tools/entrypoint.sh: line 11: 8 Aborted 发布于 2022-06-08 11:07:08
mem::forget()必须有自己的价值。如果您为它提供了一个引用,它将忘记引用--这是没有意义的,因为引用无论如何都没有Drop胶水。您必须使用mem::forget(value),而不是mem::forget(&value),但是如果您离开了value,就无法返回它。
你想做的根本是不可能的。如果一个值不实现Copy,就不能正确地复制它。即使只是ptr::read(),它也可能使原始值失效,即使您立即对其进行forget() (这件事还没有决定)。事后使用它是不可能的。
https://stackoverflow.com/questions/72544574
复制相似问题