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

Rust, how do i correctly free heap allocated memory?

I wanted to reinvent the wheel(reference counting smart pointer) and i am not sure how to properly free the memory leaked with Box::into_raw() , once the references go to zero i don’t know how to efficiently free the memory that is being pointed

I originally went with

impl<T> Drop for SafePtr<T>{
    fn drop(&mut self) {
        //println!("drop, {} refs", self.get_refs());
        self.dec_refs();
        let ref_count = self.get_refs();
        if ref_count == 0usize{
            unsafe{
                let _ = Box::from_raw(self.ptr);
                let _ = Box::from_raw(self.refs);
            };
            println!("Dropped all pointed values");
        };
    }
}

but i was wondering if ptr::drop_in_place() would work the same if not better since it won’t have to make a Box just to drop it

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 :

As you can see from the documentation on into_raw just drop_in_place is not enough, to free the memory you also have to call dealloc:

use std::alloc::{dealloc, Layout};
use std::ptr;

let x = Box::new(String::from("Hello"));
let p = Box::into_raw(x);
unsafe {
    ptr::drop_in_place(p);
    dealloc(p as *mut u8, Layout::new::<String>());
}

For performance considerations, both methods compile to the exact same instructions, so I’d just use drop(Box::from_raw(ptr)) to save me the hussle remembering the dealloc where applicable.

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