Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double-free error when using std::ptr::read in Rust

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     
like image 701
aiocat Avatar asked Aug 25 '26 19:08

aiocat


1 Answers

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.

like image 187
Chayim Friedman Avatar answered Aug 28 '26 22:08

Chayim Friedman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!