3 ms·
> In a secure Rust development, the code must not leak memory or resource in particular via Box::leak. Uh, so is Box::leak forbidden in general? Because creati
by liftm 4y ago
> In a secure Rust development, the code must not leak memory or resource in particular via Box::leak.
Uh, so is Box::leak forbidden in general? Because creating a &'static in some initialization code that lives for the rest of the program is a rather common use case… https://docs.rs/log/0.4.17/src/log/lib.rs.html#1408 https://docs.rs/log/0.4.17/src/log/lib.rs.html#1408
Or is it only forbidden if it's actually a leak?
- alpaca128 4y ago> creating a &'static in some initialization code that lives for the rest of the program is a rather common use case Isn't that the use-case for lazy_static? Or SyncOnceCell once it's in stable Rust. Though I'm not sure how it's implemented under the hood.
- liftm 4y agoHm, good point. (It's implemented as a Once (which is an atomic usize) and an UnsafeCell for holding the actual data.) And while using SyncOnceCell normally might incur some small checking overhead on each access, you can use it to obtain a &'static. https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=506632ca984ccc6732114373c535ce28 https://play.rust-lang.org/?version=nightly&mode=debug&editi... But then, by tialaramex's logic, isn't it just as bad as Box::leak? (Maybe not quite as, because it can leak maximally one thing. You can't do this in a loop.)
- tialaramex 4y agoI mean, it is actually a leak, that's exactly why you're doing it. This document says you should not because, by their definition, that's not "secure Rust development".
- mlindner 4y agoHow is it a leak if it still has a reference? I only would classify something as a leak if it has no remaining valid references to some piece of data.
- tialaramex 4y agoIt's usually considered a leak if we can't release it. Arguably you can release the thing you leaked with Box::leak(). Just tell Box you want a new box that's just a thin wrapper for your mutable reference (this is unsafe), then drop the box. But generally the purpose of Box::leak() is to never release the thing inside the box. So, yes, you could argue semantically about whether this is "really" a leak but in practice that's why it's named Box::leak()
- mlindner 4y agoMy definition of leak would generally be what Valgrind would call a leak. Wouldn't Valgrind not call this a leak given that there would still be a reference remaining at program exit?
- kaba0 4y agoIf my understanding is correct, the reference could get dropped at the end of the scope while the pointed at memory location will remain in memory - so Valgrind would leak it, but I haven’t tested it.
- pornel 4y agoBecause when you drop that reference, the memory won't be reclaimed, and destructors won't run. References in Rust aren't like references in GC languages. They don't control object's lifetime.