Repository navigation
String::as_mut_ptr is invalidated in unexected ways #158166
Description
Activity
- addedneeds-triageThis issue may need triage. Remove when done. See docs forge.rust-lang.org/release/issue-triagingThis issue may need triage. Remove when done. See docs forge.rust-lang.org/release/issue-triaging
on Jun 20, 2026 - addedC-enhancementCategory: An issue proposing an enhancement or a PR with one.Category: An issue proposing an enhancement or a PR with one.A-collectionsArea: `std::collections`Area: `std::collections`T-libs-api[DEPRECATED; DO NOT USE][DEPRECATED; DO NOT USE]A-strArea: str and StringArea: str and StringA-raw-pointersArea: raw pointers, MaybeUninit, NonNullArea: raw pointers, MaybeUninit, NonNullT-opsemRelevant to the opsem teamRelevant to the opsem teamS-waiting-on-t-libs-api[DEPRECATED; DO NOT USE][DEPRECATED; DO NOT USE]and removedneeds-triageThis issue may need triage. Remove when done. See docs forge.rust-lang.org/release/issue-triagingThis issue may need triage. Remove when done. See docs forge.rust-lang.org/release/issue-triagingS-waiting-on-t-libs-api[DEPRECATED; DO NOT USE][DEPRECATED; DO NOT USE]
on Jun 20, 2026 Would similar inherent methods need to be added to every collection in the broader ecosystem that is able to Deref to (or otherwise present as) a slice?
Would similar inherent methods need to be added to every collection in the broader ecosystem that is able to Deref to (or otherwise present as) a slice?
If they want raw pointers that are not invalidated by further calls to
as_mut_ptr, then yes.Cc @lcnr since we talked a bit about this at RustWeek.
That feels like a rather unfortunate footgun, especially given the potential number of people it could hit (many different crate authors, and their users)
Yeah, mixing references and raw pointers is fraught with peril. Not much we can do about that unless we want to give up on a good chunk of the optimizations that reference types could enable. The UCG issue for this is rust-lang/unsafe-code-guidelines#450.
Based on what we can see with Miri, this is not very common in practice.
Reacted by Steven Malis- addedT-libsRelevant to the library team, which will review and decide on the PR/issue.Relevant to the library team, which will review and decide on the PR/issue.and removedT-libs-api[DEPRECATED; DO NOT USE][DEPRECATED; DO NOT USE]
on Aug 12, 2026
This code has UB under both Stacked and Tree Borrows:
The corresponding code with
Vecis fine, becauseVec::as_mut_ptravoids invalidating previously created raw pointers to the vec's contents.String::as_mut_ptrdoes not exist, the code above relies onDerefMut for Stringandstr::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_ptronStringas well?Also see #97483, #106593