Skip to content

"Use instead" example for as_ptr_cast_mut has undefined behavior #10628

@SamZhang3

Description

@SamZhang3

Description

The documentation for the as_ptr_cast_mut lint suggests the following as an example of correct code:

let mut string = String::with_capacity(1);
let ptr = string.as_mut_ptr();
unsafe { ptr.write(4) };

However, running this code in Miri on the playground gives the following error, indicating undefined behavior:

error: Undefined Behavior: attempting a write access using <2996> at alloc1527[0x0], but that tag does not exist in the borrow stack for this location
 --> src/main.rs:4:14
  |
4 |     unsafe { ptr.write(4) };
  |              ^^^^^^^^^^^^
  |              |
  |              attempting a write access using <2996> at alloc1527[0x0], but that tag does not exist in the borrow stack for this location
  |              this error occurs as part of an access at alloc1527[0x0..0x1]
  |
  = help: this indicates a potential bug in the program: it performed an invalid operation, but the Stacked Borrows rules it violated are still experimental
  = help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information
help: <2996> would have been created here, but this is a zero-size retag ([0x0..0x0]) so the tag in question does not exist anywhere
 --> src/main.rs:3:15
  |
3 |     let ptr = string.as_mut_ptr();
  |               ^^^^^^^^^^^^^^^^^^^
  = note: BACKTRACE (of the first span):
  = note: inside `main` at src/main.rs:4:14: 4:26

note: some details are omitted, run with MIRIFLAGS=-Zmiri-backtrace=full for a verbose backtrace

error: aborting due to previous error

Version

No response

Additional Labels

@rustbot label +A-documentation

Activity

asquared31415

asquared31415 commented on Apr 11, 2023

@asquared31415
Contributor

This is mostly related to rust-lang/rust#97483 if that existed, it would not be UB.

added a commit that references this issue on Apr 12, 2023
d9c2957
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-documentationArea: Adding or improving documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      Participants

      @asquared31415@rustbot@SamZhang3

      Issue actions

        "Use instead" example for `as_ptr_cast_mut` has undefined behavior · Issue #10628 · rust-lang/rust-clippy