Why core::ptr::offset is unsafe?

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.

  1. The LLVM getelementsptr inbounds puts the strict restriction on pointer offset.
  2. 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.

In brief [1] it is GEP.


  1. on mobile ↩︎

4 Likes

Thanks a lot

Note that 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 offset and wrapping_offset as the unsafe and safe versions. It would have been possible for it to be offset and 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 *p.offset(1).

(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.)

2 Likes

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.