As can be seen from doc, core::ptr::offset is an unsafe function. But learning from unsafe rust book, the unsafe ability includes deferencing a raw pointer, not including calculating raw pointer offset. Whoever dereferences a raw pointer is responsible for its safety.
So my question is, why this function is unsafe?
Since core::ptr::offset internally uses compiler intrinsics, I don't know the exact implementation details. After consulting some online documentations, I have some guesses.
- The LLVM getelementsptr inbounds puts the strict restriction on pointer offset.
- To meet the requirements of strict provenance, which forces the resulted pointer must have the same provenance as the original pointer.
But I don't know the exact reason.
pointer::wrapping_add is not unsafe
It's because it's easier to optimize when you promise to LLVM that you're not moving the pointer to weird places -- for example,
offset is UB if you try to make a pointer wrap around the end of the address space.
So today there's
wrapping_offset as the unsafe and safe versions. It would have been possible for it to be
offset_unchecked, more like the integer methods, but in unsafe code it's generally not a great hardship to meet the soundness requirements. After all, if you know that the dereference in
*p.wrapping_offset(1) is sound, then you probably know that it could have just been
(Not always, mind you -- you might have moved the pointer outside the allocation earlier -- but most "reasonable" things to do with pointers are fine with the "pointer arithmetic is unsafe" version, so it got the shorter name.)
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.