Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
SamZhang3 opened this issue Apr 11, 2023 · 1 comment · Fixed by #10629
Closed

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

SamZhang3 opened this issue Apr 11, 2023 · 1 comment · Fixed by #10629
Labels
A-documentation Area: Adding or improving documentation

Comments

@SamZhang3
Copy link

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

@rustbot rustbot added the A-documentation Area: Adding or improving documentation label Apr 11, 2023
@asquared31415
Copy link
Contributor

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

@bors bors closed this as completed in d9c2957 Apr 12, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-documentation Area: Adding or improving documentation
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants