fn main() {
println!(
"String occupies {} bytes on the stack.",
std::mem::size_of::<String>()
);
{
let p = String::from("abcde");
println!("p at {:p}", &p);
}
let s = String::from("klmno");
println!("s at {:p}", &s);
let r = String::from("uvwxy");
println!("r at {:p}", &r);
}
output when i run cargo build --release and then run it
String occupies 24 bytes on the stack.
p at 0x609374fc00
s at 0x609374fbb8
r at 0x609374fc00
and in case when i don't use the scopes all are assigned different location
can you help me understand the memory handling as i thought compiler in case of scopes not given it would itself figure out , but even in case when scopes are given it doesn't reuse stack memory for s but instead for r
Swapping the location of s and r on the stack would result in the same amount of stack being used, so there's no reason for the compiler to prefer one over the other.
Variables s and r cannot use the same stack location because of their destructors. The following snippet has the destructors inserted:
fn main() {
println!(
"String occupies {} bytes on the stack.",
std::mem::size_of::<String>()
);
{
let p = String::from("abcde");
println!("p at {:p}", &p);
drop(p);
}
let s = String::from("klmno");
println!("s at {:p}", &s);
let r = String::from("uvwxy");
println!("r at {:p}", &r);
drop(r);
drop(s);
}