How do I free memory? #205
-
Lets say I have a function: #[ffi_export]
pub fn hello_world() -> str_boxed {
String::from("hello world").into()
}
// converts to:
// slice_boxed_uint8_t hello_world(); And I'm calling it from C code. It's caller's responsibility to free returned string now, but how to do so? Can C code Or do I have to provide explicit |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Beta Was this translation helpful? Give feedback.
The short answer is no: the allocator machinery/implementation that Rust uses for things such as
Box
es,Vec
s, etc. (i.e., the registeredimpl GlobalAlloc
), can be fully independent oflibc
/posixmalloc/free
, and thusfree()
may not be the appropriate memory-releasing operation (and UB could ensue!).The longer, and more hopeful answer, is that, when compiling a Rust binary, be it a
[bin]
ary standalone executable, or a"cdylib", "staticlib"
"C" library, you can override the default behavior of Rust allocations via the#[global_allocator]
directive. By doing so, you can then specify that all allocations g…