I am passing a raw pointer to two different closures and converting the raw pointer to a reference using Box::from_raw()
and the program is working fine.
However, after converting the raw pointer to reference, the destructor should be called automatically as the documentation says:
This function is unsafe because improper use may lead to memory problems. For example, a double-free may occur if the function is called twice on the same raw pointer.
However, I am able to access the reference to ABC even after calling Box::from_raw()
on raw pointer twice and it's working fine.
struct ABC {}
impl ABC {
pub fn new() -> ABC {
ABC {}
}
pub fn print(&self, x: u32) {
println!("Inside handle {}", x);
}
}
fn main() {
let obj = ABC::new();
let const_obj: *const ABC = &obj;
let handle = |x| {
let abc = unsafe { Box::from_raw(const_obj as *mut ABC) };
abc.print(x);
};
handle(1);
let handle1 = |x| {
let abc = unsafe { Box::from_raw(const_obj as *mut ABC) };
abc.print(x);
};
handle1(2);
}
Why is the destructor is not called for ABC
after handle
and before handle1
as the description for Box::from_raw()
function specifies:
Specifically, the
Box
destructor will call the destructor ofT
and free the allocated memory.
Why is Box::from_raw()
working multiple times on a raw pointer?