logoalt Hacker News

NohatCoderyesterday at 9:12 AM3 repliesview on HN

Yeah, one needs to understand that "unsafe" does not mark which parts of the code are actually unsafe, it simply marks parts where the compiler ignores parts of its rule set. But the implications can crop up anywhere, there is no guarantee that a resulting use-after-free or similar can only happen inside the unsafe blocks.

In short, if you use an unsafe block, then potentially any part of your code is unsafe.


Replies

josephgyesterday at 10:11 AM

> In short, if you use an unsafe block, then potentially any part of your code is unsafe.

The way I think about it is that the unsafe keyword is a promise that you’re going to maintain the safety invariants yourself, manually. The program is memory correct if it correctly maintains a certain set of invariants. Unsafe punts responsibility over those invariants to the programmer. If you use unsafe and mess up, the program may be in an invalid state. Yes - it might crash, anywhere. But the bug is still almost always in an unsafe block.

It’s often possible to make fully safe wrappers around unsafe code which maintains all those invariants manually. (Either statically or dynamically.). A lot of the rust standard library does this. For example, Vec, Box and slice all use unsafe code internally to create safe APIs.

show 1 reply
dwatttttyesterday at 11:37 AM

> it simply marks parts where the compiler ignores parts of its rule set

This is a common misconception, in a literal interpretation. It doesn't invalidate your point, but since people get the wrong impression: unsafe doesn't turn off any of the checks the Rust compiler does.

It allows you to perform 5 additional operations, and that's it. Using those operations wrong is what breaks the safety promises of the language. As an example, you could dereference a raw pointer and tell the Rust compiler it lives forever, when it's really a pointer to an object that's about to be freed.

randysalamiyesterday at 2:33 PM

Right, so if I understand correctly, to make the code fully safe, it can be impossible? Because you have underlying dependencies which are unsafe. The best you can do is make the handling of the unsafe as safe and as restricted as possible. But I can imagine some of these are way more difficult than others, and in programming the last 10% can be the last 90% of the work. Alas in terms of perceptions, the argument works well.

show 1 reply