How to stop memory leaks when using `as_ptr()`?

后端 未结 1 1102
耶瑟儿~
耶瑟儿~ 2020-12-04 01:40

Since it\'s my first time learning systems programming, I\'m having a hard time wrapping my head around the rules. Now, I got confused about memory leaks. Let\'s consider an

相关标签:
1条回答
  • 2020-12-04 02:09

    Your Rust function do_something constructs a temporary CString, takes a pointer into it, and then drops the CString. The *const c_char is invalid from the instant you return it. If you're on nightly, you probably want CString#into_ptr instead of CString#as_ptr, as the former consumes the CString without deallocating the memory. On stable, you can mem::forget the CString. Then you can worry about who is supposed to free it.

    Freeing from Python will be tricky or impossible, since Rust may use a different allocator. The best approach would be to expose a Rust function that takes a c_char pointer, constructs a CString for that pointer (rather than copying the data into a new allocation), and drops it. Unfortunately the middle part (creating the CString) seems impossible on stable for now: CString::from_ptr is unstable.

    A workaround would to pass (a pointer to) the entire CString to Python and provide an accessor function to get the char pointer from it. You simply need to box the CString and transmute the box to a raw pointer. Then you can have another function that transmutes the pointer back to a box and lets it drop.

    0 讨论(0)
提交回复
热议问题