Search code examples
rustrust-cargoborrow-checker

How are Rust references stores in Memory (Specifically Stack)


I have been learning about references in Rust and finding it hard to understand as on how exactly are references been stored in stack.

Consider the below program:

fn main() {
    let name = String::from("Somu");
    let name_ref = &name;
}

Now, How does memory is allocated in the stack frame for these 2 variables?

|--------------------|
| name     | 0x1fcd  |
|--------------------|
| name_ref | ?       |
|--------------------|

So, since String are stored in heap, we have the address of heap where the string "Somu" is present as the value for the variable name.

Now, name_ref is a reference to name. In Rust terms, name_ref borrows the value pointed by name.

So what get's stored in the stack frame as the value for name_ref?

  • Address to the heap memory containing the string?
  • Address of name in stack?

Or something else?

Can someone please enrich me with the concept?

Thanks in advance


Solution

  • So what get's stored in the stack frame as the value for name_ref?

    Address of name in stack.

    References are pointers with some additional properties that compiler knows about during compilation (mutabiliy, aliasing, guarantee of pointing to existing object, lifetime of the borrow, etc.). But in the end they are just a plain old pointer under the hood. They have size of usize (except wide/fat pointers). And hold a memory address of the thing they point to.

    You can verify that by printing address of a pointer using {:p} formatting:

    fn main() {
        let name = String::from("Somu");
        let name_ref = &name;
        
        println!("{:p}", &name as *const _);
        println!("{:p}", name_ref);
        println!("{:p}", name.as_bytes() as *const _);
    }
    

    This could for example output:

    0x7ffff3dd1350
    0x7ffff3dd1350
    0x55dfd62769d0
    

    Where two first addresses are addresses of stack variable name and third address is an address of a heap allocation that String manages.