3 ms·
The difference is that in Rust you can build safe (foolproof) abstractions on top unsafe code. OTOH, in C you can't write a library that returns a pointer and p
by pornel 5y ago
The difference is that in Rust you can build safe (foolproof) abstractions on top unsafe code. OTOH, in C you can't write a library that returns a pointer and prevents users from misusing it (e.g. ensure they can't use it after your lib frees the data, or improperly share it between threads). In C, the risk of unsafety and misuse of APIs remains a problem for every downstream user.
For example, Rust's String type internally allocates, reallocates, and frees memory. It can have partially uninitialized buffer, and lots of other "unsafe" things.
But there's no way to cause UB when using safe Rust's String. You can't cause use-after-free. You can't cause a data race. You can't overflow the buffer. You can't even break its UTF-8 encoding. That's because String's public interface only exposes safe methods. The unsafe String internals were written and checked for correctness, and from then on they're safe to use for everyone else.
- kristianp 5y agoAren't they saying though, that there could be a bug in the string unsafe code that causes UBs. You can't guarantee that (although this example is unlikely).
- jhanschoo 5y agoThat is true in general. But 1. unsafe code in the standard library is of course more battle-tested than ad-hoc unsafe code, and 2. there are efforts to formally verify Rust. http://plv.mpi-sws.org/rustbelt/ http://plv.mpi-sws.org/rustbelt/ and https://internals.rust-lang.org/t/announcing-the-formal-verification-working-group/7240 https://internals.rust-lang.org/t/announcing-the-formal-veri...
- littlestymaar 5y agoThere could, and these kind of bugs have happened a few times already, but fortunately they are few and far between, and as the sibling comment mentioned there's some work in progress to formal prove the std lib, and because the std lib is much smaller than the amount of code that uses the stdlib, it's much less work to formally verify the stdlib than it would be to verify for instance all C++ programms using the C++ stdlib. [1]: the most famous bug in the standard library exposing an unsound construction is the “leakpocalypse”: https://github.com/rust-lang/rust/issues/24292 https://github.com/rust-lang/rust/issues/24292
- pornel 5y agoThere's a practical difference in how much of the program is high risk. If all of the risk is concentrated in a few functions, it's easier to focus on reviewing/testing/fuzzing these bits. Rust changes the bug-spotting game from "Where's Waldo?" to "Is this a Waldo?"