Skip to content

Cloning &strs doesn't trigger borrow checker #19704

@Manishearth

Description

@Manishearth
Member

MWE:

fn get() -> Option<String> {
 Some("hi".to_string())
}

fn main() {
 let y = match get() {
  Some(x) => x.as_slice().clone(),
  None => "hello"
 };
 let mut z = "something".to_string();
 for i in range(1,1000u) {
   z = format!("{}", i);
   println!("{}", z)
 }
 println!("{}", y)
}

The last thing it prints out should be "hi". Instead it prints out "99" -- it it looks like the String x is deallocated in the match, but the pointer to the freed memory lives on.

Activity

Manishearth

Manishearth commented on Dec 10, 2014

@Manishearth
MemberAuthor

Changing "hi" to a longer string leads to varying results (I guess it's allocating different-sized Strings in different areas, which sounds logical)

pcwalton

pcwalton commented on Dec 10, 2014

@pcwalton
Contributor
Manishearth

Manishearth commented on Dec 10, 2014

@Manishearth
MemberAuthor

More minimal MWE:

fn main() {
 let y = {
  // "hello world" allocated
  "hello world".to_string().as_slice().clone()
  // "hello world" deallocated
 };
 // new string allocated in same spot
 let z = "something".to_string();
 println!("{}", y)
 // prints "somethingld"
}

I suspect results may vary depending on your system, but fiddling with the string length works.

sfackler

sfackler commented on Dec 10, 2014

@sfackler
Member

Looks like a dup of #19261

Manishearth

Manishearth commented on Dec 10, 2014

@Manishearth
MemberAuthor

Seems correct.

added a commit that references this issue on May 5, 2025
bb906cc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @pcwalton@sfackler@Manishearth

        Issue actions

          Cloning `&str`s doesn't trigger borrow checker · Issue #19704 · rust-lang/rust