In Rust (and really C/C++ too but they use different terminology) there is a concept of pointer provenance. Generally it is safe to:
- Take a pointer to some existing allocation
- Do math on the pointer that keeps it within the bounds of that allocation
- Dereference the pointer
But doing math on it that puts it outside the original allocation and then dereferencing it is UB. But sometimes when doing low level programming you want to hard code that a particular memory address is used for something. The obvious way to write that is something like:
let p = 0xDEADBEEF as *mut i32;
But then can I dereference p
? There may never be any explicit allocation done from Rust's perspective at that address. Even if there were, if we don't want the overhead of explicitly storing a pointer when we already know the address, we would probably do the above to make the pointer "from scratch" fairly often rather than letting the provenance be transferred by copying the pointer we got from the allocation function. Is this allowed in Rust's memory model at all? To be clear I'm not asking about lifetime, for purposes of this discussion we can assume everything at the address is 'static
.