diff --git a/library/alloc/src/ffi/c_str.rs b/library/alloc/src/ffi/c_str.rs index b2f4277458f1..e6e6fcf5420f 100644 --- a/library/alloc/src/ffi/c_str.rs +++ b/library/alloc/src/ffi/c_str.rs @@ -1077,9 +1077,17 @@ fn to_owned(&self) -> CString { } fn clone_into(&self, target: &mut CString) { - let mut b = mem::take(&mut target.inner).into_vec(); - self.to_bytes_with_nul().clone_into(&mut b); - target.inner = b.into_boxed_slice(); + let src = self.to_bytes_with_nul(); + // If the lengths match, we can reuse the existing allocation without any overhead. + if target.inner.len() == src.len() { + target.inner.copy_from_slice(src); + } else { + // Reuse the existing allocation's capacity by converting to a Vec. + // We temporarily replace `target` with a valid dummy to remain panic-safe. + let mut b = mem::replace(&mut target.inner, Box::new([0])).into_vec(); + self.to_bytes_with_nul().clone_into(&mut b); + target.inner = b.into_boxed_slice(); + } } }