# Unsafe question

**URL:** <https://users.rust-lang.org/t/unsafe-question/39718>\
**Category:** help\
**Created:** [March 20, 2020, 1:09am UTC](https://users.rust-lang.org/t/unsafe-question/39718 "2020-03-20T01:09:03Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![konsumlamm](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/konsumlamm/32/14693_2.png) [@konsumlamm](https://users.rust-lang.org/u/konsumlamm)\
**Post date:** [March 20, 2020, 1:09am UTC](https://users.rust-lang.org/t/unsafe-question/39718/1 "2020-03-20T01:09:03Z")

</div>

Let's say i have a struct with two fields:

```rust
struct Foo {
    a: i32,
    b: bool,
}

```

Now, assume `ptr ` is a `*const Foo` (due to variance) that points to a valid `Foo`. Would this be safe?

```rust
use std::ptr::NonNull;

unsafe fn f(ptr: NonNull<Foo>) {
    // modify the b field
    ptr.as_mut().b = true;
}

unsafe {
    let foo = &*ptr;
    f(NonNull::from(foo)); // (1)
    let res = &foo.a; // (2)
    // use res
}

```

If not, would it make a difference if (1) and (2) are swapped?  
And would it be safe if I passed `NonNull::new_unchecked(ptr as *mut Foo)` to `f` instead?

---

<div class="post-metadata">

**Author:** ![RustyYato](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/rustyyato/32/49247_2.png) [@RustyYato](https://users.rust-lang.org/u/RustyYato)\
**Post date:** [March 20, 2020, 1:11am UTC](https://users.rust-lang.org/t/unsafe-question/39718/2 "2020-03-20T01:11:06Z")

</div>

You cannot write to a pointer derived from a `&T` unless you pass through a `UnsafeCell`. (which you are not doing in this case). You can do a simple check of your code using [miri](https://github.com/rust-lang/miri) (this also works on playground under the tools dropdown). miri is not perfect, so it won't catch all your mistakes, but if it complains then you are almost certainly making a mistake.

---

<div class="post-metadata">

**Author:** ![konsumlamm](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/konsumlamm/32/14693_2.png) [@konsumlamm](https://users.rust-lang.org/u/konsumlamm)\
**Post date:** [March 20, 2020, 1:15am UTC](https://users.rust-lang.org/t/unsafe-question/39718/3 "2020-03-20T01:15:48Z")

</div>

> [@RustyYato](#):
>
> You cannot write to a pointer derived from a `&T` unless you pass through a `UnsafeCell` .

Does that still hold when the `&T` comes from a raw pointer?

---

<div class="post-metadata">

**Author:** ![RustyYato](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/rustyyato/32/49247_2.png) [@RustyYato](https://users.rust-lang.org/u/RustyYato)\
**Post date:** [March 20, 2020, 1:19am UTC](https://users.rust-lang.org/t/unsafe-question/39718/4 "2020-03-20T01:19:12Z")

</div>

Yes, even if it came from a raw pointer. References in Rust have quite a few invariants attached to them, so don't treat them like pointers. Another example is: `&mut T` is an exclusive reference that may not be aliased by any unrelated pointer.

See the rust nomicon for more info about unsafe, and stacked borrows for the closest thing Rust has to an aliasing model.

---

<div class="post-metadata">

**Author:** ![TomP](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/tomp/32/4735_2.png) [@TomP](https://users.rust-lang.org/u/TomP)\
**Post date:** [March 20, 2020, 1:28am UTC](https://users.rust-lang.org/t/unsafe-question/39718/5 "2020-03-20T01:28:13Z")

</div>

Unspecified Behavior (UB) is like [Russian roulette](https://en.wikipedia.org/wiki/Russian_roulette); each time you recompile (because you made a change, or a library changed, or there is a new release of the compiler) you are spinning the barrel and pulling the trigger again. You might be lucky in the short term, but your luck won't last.

---

<div class="post-metadata">

**Author:** ![trentj](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/trentj/32/5690_2.png) [@trentj](https://users.rust-lang.org/u/trentj)\
**Post date:** [March 20, 2020, 2:06am UTC](https://users.rust-lang.org/t/unsafe-question/39718/6 "2020-03-20T02:06:12Z")

</div>

Note that the following might (potentially, keep reading) be fine:

```rust
unsafe {
    let foo = &mut *(ptr as *mut _);
    f(NonNull::from(foo)); // (1)
    let res = &foo.a; // (2)
    // use res
}

```

Raw pointers have no aliasing rules, and raw pointer mutability is more like a _suggestion_ than a rule, per se (they're much like C pointers in that respect). It's fine to cast a `*const T` to a `*mut T` temporarily and mutate the `T` through that. There are still a lot of ways this can go wrong, though; off the top of my head:

1. You have to get the `*const T` initially in a way that allows you to mutate through it. In practice this means you have to get it by casting a `*mut T` that you got by taking a `&mut T`.
2. Even though you're using raw pointers, you still have to honor the terms of all the borrow expressions in your program. So assuming you do what I just suggested and get the `*const T` by casting a `&mut T`, you can't have any _other_ references to the same `T` that weren't derived from that `&mut` borrow until you are done using it. Swapping lines (1) and (2) also technically breaks this rule because it creates a mutable reference that aliases a shared reference. **Even using raw pointers, you're still not allowed to violate the rules of references.**
3. You mentioned it's `*const T` and not `*mut T` because of variance. Variance is another way this can go wrong. If `T` is something like `Foo<'long>` and variance shrinks it down to `Foo<'short>`, a function similar to `f` could theoretically stuff a `&'short` into a slot labeled `&'long`, which would lead to unsoundness if the reference is then followed outside its proper lifetime. I don't think this can happen with the given `f` because `b` is just a `bool`, so you might be in the clear. It depends on how close this is to your real code.

---

<div class="post-metadata">

**Author:** ![alice](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/alice/32/9777_2.png) [@alice](https://users.rust-lang.org/u/alice)\
**Post date:** [March 20, 2020, 9:34am UTC](https://users.rust-lang.org/t/unsafe-question/39718/7 "2020-03-20T09:34:34Z")

</div>

Basically if you want a raw pointer you can write through, you need to create it from a `&mut` reference.

---

<div class="post-metadata">

**Author:** ![konsumlamm](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/konsumlamm/32/14693_2.png) [@konsumlamm](https://users.rust-lang.org/u/konsumlamm)\
**Post date:** [March 20, 2020, 10:33am UTC](https://users.rust-lang.org/t/unsafe-question/39718/8 "2020-03-20T10:33:46Z")

</div>

Ok, so i assume this

```rust
unsafe {
    let foo = &*ptr;
    f(NonNull::new_unchecked(ptr as *mut Foo)); // (1)
    let res = &foo.a; // (2)
    // use res
}

```

would be UB as well?

> [@alice](#):
>
> Basically if you want a raw pointer you can write through, you need to create it from a `&mut` reference.

Using `Box::into_raw` works too, right?

---

<div class="post-metadata">

**Author:** ![RustyYato](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/rustyyato/32/49247_2.png) [@RustyYato](https://users.rust-lang.org/u/RustyYato)\
**Post date:** [March 20, 2020, 12:09pm UTC](https://users.rust-lang.org/t/unsafe-question/39718/9 "2020-03-20T12:09:14Z")

</div>

> [@konsumlamm](#):
>
> would be UB as well?

Yes

> [@konsumlamm](#):
>
> Using `Box::into_raw` works too, right?

Yes, you can also write to a raw pointer obtained from an `UnsafeCell`.

---

<div class="post-metadata">

**Author:** ![trentj](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/trentj/32/5690_2.png) [@trentj](https://users.rust-lang.org/u/trentj)\
**Post date:** [March 20, 2020, 12:15pm UTC](https://users.rust-lang.org/t/unsafe-question/39718/10 "2020-03-20T12:15:58Z")

</div>

> [@konsumlamm](#):
>
> Ok, so i assume this [...] would be UB as well?

I wasn't 100% sure about this, because there could be an argument that the borrow `&*ptr` doesn't get "used" until it's safe to do so, but [Miri doesn't like it](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=186d0390f31fe66f016e2d5de6d5bb21) (go to Tools -\> Miri):

```plaintext
error: Miri evaluation error: trying to reborrow for SharedReadOnly, but parent tag <1563> does not have an appropriate item in the borrow stack
  --> src/main.rs:16:15
   |
16 | let res = &foo.a; // (2)
   | ^^^^^^ trying to reborrow for SharedReadOnly, but parent tag <1563> does not have an appropriate item in the borrow stack
   |
note: inside call to `bar` at src/main.rs:23:9
  --> src/main.rs:23:9
   |
23 | bar(&mut obj as *mut _);
   | ^^^^^^^^^^^^^^^^^^^^^^^
   = note: inside call to `main` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/src/libstd/rt.rs:67:34:

```

I take this to mean that creating the `&mut` inside `f` forcibly ends the earlier, shared borrow, after which it's invalid to try to use `foo` again. (The version I posted earlier, with a small tweak, [does run without errors](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=b518386f249b4d56c81ef626ea930830).)

You can use Miri to check your assumptions about the [borrowing model](https://plv.mpi-sws.org/rustbelt/stacked-borrows/), but be careful -- testing your code in Miri is not a sure way to guarantee it will never have undefined behavior.

---

<div class="post-metadata">

**Author:** ![Yandros](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/yandros/32/8136_2.png) [@Yandros](https://users.rust-lang.org/u/Yandros)\
**Post date:** [March 20, 2020, 12:39pm UTC](https://users.rust-lang.org/t/unsafe-question/39718/11 "2020-03-20T12:39:13Z")

</div>

Yes, even if you avoid the UB of mutating through a (pointer that originated from a) `&` reference, you still cannot swap the lines, otherwise it would be a violation of Stacked Borrows; see [this post](https://users.rust-lang.org/t/the-confessional-thread-parts-of-rust-that-i-still-dont-get-after-all-this-time/39022/8) for an explanation.

---

<div class="post-metadata">

**Author:** ![mbrubeck](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/mbrubeck/32/648_2.png) [@mbrubeck](https://users.rust-lang.org/u/mbrubeck)\
**Post date:** [March 20, 2020, 5:16pm UTC](https://users.rust-lang.org/t/unsafe-question/39718/12 "2020-03-20T17:16:55Z")

</div>

There are some recent discussions on the Internals forum that are relevant here:

> **[Pre-RFC: Struct/union raw pointer field access](https://internals.rust-lang.org/t/pre-rfc-struct-union-raw-pointer-field-access/11546)**
>
> Hi, I would like to ask your opinions on this alternative RFC #2582 (&raw operator) proposal. Summary Allow accessing fields in raw pointers pointing to structs or unions. Such an operation would create a raw pointer. Motivation Rust doesn't...

> **[Need for -\> operator for Unsafe Code Guidelines](https://internals.rust-lang.org/t/need-for-operator-for-unsafe-code-guidelines/10022)**
>
> I lost a long detailed draft of this, so I’ll keep it short this time. In my experience, the two most common miri-caught violations of the Unsafe Code Guidelines we have are: We materialize or hold onto a too-large reference when working with raw...

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [June 18, 2020, 5:16pm UTC](https://users.rust-lang.org/t/unsafe-question/39718/13 "2020-06-18T17:16:58Z")

</div>

Closed on June 18, 2020, 5:16pm UTC

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.
