i am trying to read a value from pointer but i always get a double-free error. Do you guys know a way to fix it? I am using mem::forget to block the free operation but i still get the same result.
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
}
Error:
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
>Solution :
mem::forget() must take an owned value. If you provide it with a reference, it’ll forget the reference – which is meaningless since references do not have a Drop glue anyway. You’ll have to mem::forget(value) and not mem::forget(&value), but then you move out of value and you cannot return it.
What you’re trying to do is fundamentally impossible. You cannot duplicate a value soundly if it does not implement Copy. Even just ptr::read()ing it may invalidate the original value, even if you immediately forget() it (this is not decided yet). Using it after is a non-starter.