Why are stack values so far apart in Rust?

Viewed 74

When I run

fn main() {
    let x: i32 = 0;
    println!("{:p}", &x);
    let y: i32 = 1;
    println!("{:p}", &y);
}

in the Rust playground, the values printed are, in decimal, 88 apart. My expectation would be that they would be 4 or 8 (bytes) apart. Why is it so large?

2 Answers

The println! macro will use stack variables too. If you swap the order of your statements around (in Rust Playground debug at least), the two pointers are 4 bytes apart:

fn main() {
    let x: i32 = 0;
    let y: i32 = 1;
    println!("{:p}", &x); // 0x7ffe0b865db0
    println!("{:p}", &y); // 0x7ffe0b865db4
}

There are no guarantees about how the stack is used, and it's very likely to be different with an optimised binary.

After a small test and some reading (println is a macro) i would assume that the macro creates additional code that causes the addresses of your variables to be more than the expected 4-8 bytes appart.

Related