3 ms·
And there is a memory leak in all of that.
by GlitchMr 9y ago
And there is a memory leak in all of that.
- wging 9y agoI was going to ask, how does Node then know to free the string when all JS pointers to it are gone? ... guess it doesn't?
- webkike 9y agoWhen the program exits memory will be reclaimed by the kernel. Memory leaks aren't horrible if they don't appear in loops or recursive functions (that is to say the leaked allocations do not grow with the uptime of the program). In this case it's pretty much identical to allocating memory that has the lifetime of the program. Pretty obvious stuff but it's important to keep in mind.
- thayne 9y agoIt might be good to mention how to free the memory. By passing the pointer back to a rust function like #[no_mangle] pub extern fn free_string(p: *mut c_char) { unsafe { let _ = CString::from_raw(p); // optionally you could explicitly call drop, but // that is unnecessary, since it is automatically dropped // at end of scope } } Also the `into_raw` method on CString gives you a pointer while simultaneously taking ownership of the CString, so mem::forget isn't necessary if you use `into_raw` rather than `as_ptr`.