by EE84M3i · 5y ago · 0 comments
As a motivating example, in many languages converting a reference to an integer containing a memory address is unsafe (e.g. Java[1]/golang[2]/C#[3]/Haskell[4]), but this is considered safe in Rust.[5] All these languages literally use the word "unsafe" for it.
[1]: See sun.misc.Unsafe, which indirectly provides this https://stackoverflow.com/a/7060500/315936
[2]: https://golang.org/pkg/unsafe/#Pointer
[3]: pointer types are only allowed with the unsafe keyword, see: https://docs.microsoft.com/en-us/dotnet/csharp/programming-g...
[4]: I believe this requires unsafeCoerce https://stackoverflow.com/a/18563789/315936
Converting a pointer to an integer address is problematic if you have a garbage collector due to compacting. Technically it's still the dereferencing that actually causes the UB, but I don't think this is too much of a leap.
C# marking all pointers unsafe also makes sense in the same way, because "passing pointers between methods can cause undefined behavior."
Converting a pointer to an integer address and never dereferencing it (e.g. to print it) does not lead to U.B., but it does leak ASLR information. Some languages consider that safe (Rust) and others do not. I think that is in an important distinction.
All functions that have `unsafe` as part of their name have it because they can lead to u.b. with improper use.
Regardless, I agree the function under discussion though, "head", is not "unsafe" in either sense. That's why I said "as an aside".