Closed
Description
Location
https://doc.rust-lang.org/std/primitive.pointer.html#method.offset
Summary
Offset doc states that
If the computed offset is non-zero, then self must be derived from a pointer to some allocated object, and the entire memory range between self and the result must be in bounds of that allocated object.
allocated object doc states that
For all addresses a in addresses, a is in the range base .. (base + size) (note that this requires a < base + size, not a <= base + size)
so as i understand offsetting pointer to the head of an array one past it's length should not be allowed, but in practice it is allowed
fn main() {
static A: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
static mut B: *const u8 = unsafe {A.as_ptr().offset(8)};
}
this code compiles just fine, but this one produces an error
fn main() {
static A: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
static mut B: *const u8 = unsafe {A.as_ptr().offset(9)};
}
error[E0080]: could not evaluate static initializer
--> /home/daria/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ptr/const_ptr.rs:455:18
|
455 | unsafe { intrinsics::offset(self, count) }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ out-of-bounds pointer arithmetic: expected a pointer to 9 bytes of memory, but got alloc1 which is only 8 bytes from the end of the allocation
|
note: inside `std::ptr::const_ptr::<impl *const u8>::offset`
--> /home/daria/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ptr/const_ptr.rs:455:18
|
455 | unsafe { intrinsics::offset(self, count) }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: inside `B`
--> src/main.rs:3:39
|
3 | static mut B: *const u8 = unsafe {A.as_ptr().offset(9)};
| ^^^^^^^^^^^^^^^^^^^^