Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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     

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading