4 ms·
> I kind of wish that this pointer casting required unsafe, just because this code should send up red flags, and probably deserves a close look during code revi
by haileys 2y ago
> I kind of wish that this pointer casting required unsafe, just because this code should send up red flags, and probably deserves a close look during code review.
If a pointer cast performed in safe code can cause unsoundness in unsafe code elsewhere, that's a bug in the unsafe code. All bets are off if your unsafe code is that trusting of data it receives from safe code.
This is a good argument for why pointer casting should be safe - it forces the point and pushes you to find the right abstraction. No pointer cast done in safe code should ever be able to cause unsoundness.
- _flux 2y agoUnsafe code can rarely validate pointers it receives and must depend on the properties of the other code to work safely. It just doesn't depend on the safety properties of that other code.
- haileys 2y agoExactly. So you must use Rust's encapsulation features like modules and visibility to ensure that any particular piece of unsafe code _cannot_ receive a pointer that can't be proven to be valid.
- darby_nine 2y ago> If a pointer cast performed in safe code can cause unsoundness in unsafe code elsewhere, that's a bug in the unsafe code. Converting from pointer to integer (as in the given example) cannot possibly lead to unsafe code that would not have already been unsafe with an arbitrary integer value. There's nothing unsafe about accessing an address without dereferencing it. Casting to a pointer from an integer should probably be considered generally unsafe.
- haileys 2y ago> Casting to a pointer from an integer should probably be considered generally unsafe. The pointer can't be assumed to be valid anyway without other guarantees. It could have been valid at some point, and then freed at another point, and is now dangling. You'll notice that std::ptr::null and std::ptr::dangling are also safe functions. This is intentional - the language designers are telling you that you cannot rely on the fact that a piece of data is of a pointer type to trust that it's valid.