4 ms·
This person isn't wrong. A lot of serious Rust users don't agree with what the GP is suggesting. `unsafe` has an explicit meaning: the user must uphold some inv
by vitno 4y ago
This person isn't wrong. A lot of serious Rust users don't agree with what the GP is suggesting. `unsafe` has an explicit meaning: the user must uphold some invariant or check something about the environment, otherwise it is memory unsafe.
I have several times in code review prevented people from marking safe interfaces as "unsafe" because they are "special and concerning", overloading the usage of unsafe is itself dangerous.
- zozbot234 4y agoTrue, but I think allowing potentially UB-invoking code to not use "unsafe" (e.g. because the use is in the context of FFI, so the unsafety is thought to be "obvious" and not worth marking as such) might be even less advisable. This makes it harder to ensure the "social rule" mentioned by GP, that every potential UB should be endowed with a "Safety" annotation describing the conditions for it to be safe.
- ______-_-______ 4y agoYour comment gave me an idea for a lint that might help prevent those mistakes. Right now rustc flags `unsafe {}` with an "unused_unsafe" warning. However it doesn't warn for `unsafe fn foo() {}`. Maybe it should.
- gpm 4y agoI think as described you would get false positives, because `unsafe fn foo() { body that performs no unsafe operations }` can be unsafe to call if it interacts with private fields on datastructures used by safe (to call) functions that perform unsafe operations... I expect you would end up with a reasonably high number of false positives. For an example, consider Vec::set_len in the standard library. Which only contains safe code, but lets you access uninitialized memory and beyond the length of your allocation by modifying the length field of vector: https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1264 https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1264 You might be able to fix this with a lint that looked at a bit more context though, `unsafe fn foo()` in a module (or even crate) with no actually unsafe operations is very likely wrong. Likewise `unsafe fn foo()` which performs no unsafe operations and only accesses fields, statics, functions, and methods that are public.
- aliceryhl 4y agoThe Rust Vec type has an unsafe function called `set_len` that changes the length of the vector without checking whether the new length is in bounds, or whether the memory containing any new values is initialized. The body of the function is the following: self.len = new_len; No unsafe operations in sight. Should the compiler emit a warning here?