3 ms·
I don't understand the following sentence: > ... it is strongly recommended that you only free memory allocated by a Vec by creating a new Vec and dropping it.
by tom_mellior 9y ago
I don't understand the following sentence:
> ... it is strongly recommended that you only free memory allocated by a Vec by creating a new Vec and dropping it.
Could someone parse this for me? To me, it reads like "to free memory allocated by a Vec v, create a new Vec w and drop it (i.e., w)".
This is obviously not what it is intended. What's the role of the second Vec? Is this only in a context where v is empty but its memory not yet freed? If so, why wouldn't shrink_to_fit work in that case?
- Manishearth 9y agoThis is in case you turn the Vec into a raw pointer (using as_ptr() and mem::forget) so that you can pass ownership over FFI or something. In this case it is not recommended that you free it by calling free(), it is recommended that you free it by using from_raw_parts to reconstruct a new vector and let it drop. You need the second vec because the first vec is gone at this point. If it wasn't gone you could just let the destructor run. In Rust Vec and Box also work as the malloc primitives; if you absolutely need to allocate contiguous memory of runtime-known size the best way to do it is to allocate a Vec and then extract the pointer from it. (There is a proper allocation API coming soon; and of course you can just call malloc/free, but this is the recommended way of doing it)
- steveklabnik 9y agoI've filed a bug to elaborate, thanks! https://github.com/rust-lang/rust/issues/46879 https://github.com/rust-lang/rust/issues/46879
- tom_mellior 9y agoCool, thanks to both of you for the quick report and fix!