Need help in clarifying some things about local variables inside Rust functions

Hey guys I am newbie to rust and need some help in understanding where str is stored inside a function

fn foo(){
    let a=10;
    let word:&str="hello";
    println!("{}",word);
}


fn main(){
    
let main_str:&str="inside main";

}

As far as I understand,

When I call foo() from main it will create the variable a and word in the stack frame
where word will point to the memory location where the literal "hello" is stored.

SO when we exit the function foo() does the string literal "hello" gets destroyed or is it just the variable word and the variable a that are popped off from the stack frame?
If in the above case if the literal "hello" is not destroyed,does it create a memory leak?
Also where in memory is the literal "hello" stored? Is it on the heap,or the stack,or somewhere else?


strings in your example have 'static lifetime and stored in the bss segment of the ELF binary

1 Like

So the string inside the function will get destroyed when foo exits am I right?

No, static strings remain in the binary for the lifetime of the program.

1 Like

Your variable is just a reference to the string data. It doesn't own it so there's nothing to destroy.

1 Like

I guess it's similar to this:

static WORD: &'static str = "hello";

fn foo(){
    let a=10;
    let word:&str=WORD;
    println!("{}",word);
}


fn main(){
    
let main_str:&str="inside main";

}

(Playground)

1 Like

and by the magic of compiler/linker, any use of "hello" implicitly references this single instance

Yes, though I'm not sure if it's guaranteed that it's a single instance when you use the same string elsewhere in the program (or within linked crates).

So all subsequent invocations of foo would still refer to only a single
instance of "hello",the one created during the first function call.Am I getting
it right?

a single instance of "hello",the one created during the first function call.

No, this is not caching; the first call is not different from the others. The text hello is put into the compiled program by the compiler, and loaded into memory at the same time as the rest of the program's code (more or less). Then whenever the code containing a "hello" actually runs and produces an &str value, all it is doing is producing the address (and length) of that already-existing hello in memory.

(The same sort of process happens for every other kind of reference to a literal value, like say &[1, 2, 3, 4].)

4 Likes
So basically what the compiler does is that it gathers all the hardcoded string literals and puts
them in the read only memory to which we can get a reference when we need!

Hey thanks for the clarification and I think I understand it know!