Skip to content

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

Closed
@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

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

    No branches or pull requests

    Issue actions