r-rust/hellorust

Is the CString need to be freed?

yutannihilation opened this issue · 2 comments

This is rather a question. During exploring how to handle vectors, I found I needed to pass back the vector to Rust to deallocate it if it's allocated by Rust. I'm wondering if this CString should be freed in the same way otherwise this stays on memory forever, right...?

let s = CString::new("Hello ピカチュウ !").unwrap();

jeroen commented

Can you send a PR?

After thinking this issue again after 3 years, I have no idea what to do. Let me check if my understanding is correct.

  • CString::new() does allocate (right?), so it needs to be freed on Rust's side.
  • This C string needs to live until Rf_mkCharCE() is called, and be freed then.
  • But, since Rf_mkCharCE() is called on C's side, we cannot free it there because C and Rust might use different allocators.
  • So, we need another Rust function dedicated for freeing it by bringing the forgotten pointer back to CString() (CString::from_raw()).

Does this sound good? Honestly, I feel this is a bit advanced and might not suitable for an example package. So, accepting memory leak might be an option here (but, I think this should be explained in the code comments at least).