String::as_mut_ptr is invalidated in unexected ways
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
This code has UB under both Stacked and Tree Borrows:
fn main() {
let mut s = String::with_capacity(10);
s.push('x');
let ptr = s.as_mut_ptr();
unsafe { ptr.write(0x20) };
let _ptr2 = s.as_mut_ptr(); // creates a slice that aliases with `ptr`.
// That is considered like a read access, and since `ptr` is derived from
// a mutable reference such a foreign read access invalidates `ptr`.
unsafe { ptr.write(97) }; // UB
println!("{s:?}");
}
The corresponding code with Vec is fine, because Vec::as_mut_ptr avoids invalidating previously created raw pointers to the vec's contents. String::as_mut_ptr does not exist, the code above relies on DerefMut for String and str::as_mut_ptr, which creates some extra references that cause unexpected invalidation.
Cc @rust-lang/libs-api -- would you be open to the idea of having as_mut_ptr on String as well?
Also see https://github.com/rust-lang/rust/pull/97483, https://github.com/rust-lang/rust/issues/106593
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the issue's example and compare String's DerefMut for String and str::as_mut_ptr behavior with Vec::as_mut_ptr. Read the linked pull request and issues for prior context; done requires a resolved API decision and, if accepted, an implementation with appropriate validation, though no file or test path is named here.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- backend-api-design
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100