Closed brandonros closed 2 years ago
Hey, sorry, I have been busy these past days. Yes, there are some things to do to clean up your code, I may write a detailed post within the following days.
Right now the main offender is the moduleDataArray
which is dropped at the end of convert_module_item_rpc_to_ffi()
. In general, rather than Box::leak
and/or forget
, try to look for into_raw
-named methods in the standard library:
For Vec
and String
, which may "over"-allocated and thus have a capacity
as well, there is into_raw_parts()
:
For Box
and CString
, there is the more general into_raw()
:
A key thing for these methods is that they consume ownership (conceptually relinquishing ownership) of their input, thereby guaranteeing a lack of drop / segfault etc. (you'd later have to give the ownership back to avoid memory leaks, but while focusing on crashes caused by use-after-frees, that is not the priority):
pub fn convert_module_item_rpc_to_ffi(input: RPC_PDU_MODULE_ITEM) -> PDU_MODULE_ITEM {
let mut moduleDataArray: Vec<PDU_MODULE_DATA> = Vec::new();
for i in 0..input.NumEntries as usize {
moduleDataArray.push(convert_module_data_rpc_to_ffi(input.ModuleData[i].clone()));
}
let output = Box::new(PDU_MODULE_ITEM {
ItemType: input.ItemType,
NumEntries: input.NumEntries,
- pModuleData: moduleDataArray.as_slice().as_ptr()
+ pModuleData: Box::into_raw(moduleDataArray.into_boxed_slice()) as *mut _,
});
return *Box::leak(output);
}
If you want to keep discussing about this, feel free to head over the Discussions section of the repo 🙂
I'm sorry, I just stumbled across your library and I don't know where else to ask. I've tried "ManullyDrop", mem::forget, Box, all sorts of stuff.
What can I do to allocate a struct in a function, return it, and the allocator not like... just 100% destroy it and cause a bunch of segfaults/corruption?