You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
String::push_str invalidates interior references even when it does not reallocate #70301
To my knowledge, the following code is intended to be legal:
fnmain(){letmut buf = String::with_capacity(11);
buf.push_str("hello");let hello:&str = unsafe{&*(buf.as_str()as*const_)};// laundering the lifetime -- we take care that `buf` does not reallocate, so that's okay.
buf.push_str(" world");println!("{}", hello);}
However, Miri currently flags this as UB.
I believe this is #60847, but for String. Discovered while writing this post.
Yeah this looks pretty similar. String uses Vec under the hood though, so I wonder why the issue still exists here.
Looks like push_str is implemented via extend_from_slice -- and indeed, this errors, too:
fnmain(){letmut v = Vec::with_capacity(10);
v.push(0);let v0 = unsafe{&*(&v[0]as*const_)};// laundering the lifetime -- we take care that `v` does not reallocate, so that's okay.
v.extend_from_slice(&[1]);let _val = *v0;}
The get_unchecked_mut here is a slice method, so this creates a slice covering the entire Vec, which overlaps with the mutable reference created before and thus invalidates it.
It shouldn't be too hard to locally fix this, but that duplicates some code and there are some other uses of get_unchecked_mut in vec.rs. Ideally, this would all use raw slices to avoid making any uniqueness promises. But without #60639, raw slices are not very useful.
Activity
RalfJung commentedon Mar 23, 2020
Yeah this looks pretty similar.
StringusesVecunder the hood though, so I wonder why the issue still exists here.Looks like
push_stris implemented viaextend_from_slice-- and indeed, this errors, too:RalfJung commentedon Mar 23, 2020
The problem is in this line:
rust/src/liballoc/vec.rs
Line 2125 in 8ff7850
The
get_unchecked_muthere is a slice method, so this creates a slice covering the entireVec, which overlaps with the mutable reference created before and thus invalidates it.RalfJung commentedon Mar 23, 2020
It shouldn't be too hard to locally fix this, but that duplicates some code and there are some other uses of
get_unchecked_mutinvec.rs. Ideally, this would all use raw slices to avoid making any uniqueness promises. But without #60639, raw slices are not very useful.RalfJung commentedon Mar 23, 2020
Here's a possible fix:
RalfJung commentedon Mar 30, 2020
Fix PR is up: #70558
Rollup merge of rust-lang#70558 - RalfJung:vec-extend-aliasing, r=Ama…
Auto merge of #1253 - RalfJung:vec-extend, r=RalfJung