rust-lang / rust-lang/rust

String::as_mut_ptr is invalidated in unexected ways

Open
#158,166 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-collections A-raw-pointers A-str C-enhancement T-libs T-opsem
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.