英文:
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.
英文:
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
答案1
得分: 4
根据into_raw
文档,仅仅使用drop_in_place
是不够的,为了释放内存,你还需要调用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>()); }
出于性能考虑,这两种方法编译成完全相同的指令,所以我会使用drop(Box::from_raw(ptr))
,以避免记住何时使用dealloc
。
英文:
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
:
> rust
> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论