Can't figure out the memory handling

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

so any help would be appreciated!

What is the question?

sorry you can see the question now

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.

2 Likes

but then why scopes are needed to specify this , is compiler not capable of that optimisation ?

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);
}
3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.