Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 794
Eto on a mill Avatar asked Dec 13 '25 13:12

Eto on a mill


1 Answers

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.

like image 91
cafce25 Avatar answered Dec 16 '25 22:12

cafce25



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!