Question: Why does Rust reverse the order of variables on the stack?
Hello, recently I've enrolled in a systems class at college (I'm enjoying it very much). We recently learned about how variables are stored on the stack in C and how the compiler will pad extra space between variables so it's more efficient for the CPU to access values within the system word size.
I've programmed in Rust before but this class has helped motivate me to try some experiments to get a better grasp of lower-level system functionality.
TLDR: Anyway, I ran some experiments and I was confused as to why Rust reverses the order of how variables are pushed onto the stack.
This is the code I ran:
Rust:
fn main() {
let x: i32 = 0;
let y: i16 = 0;
let z: i32 = 0;
println!("x -> {:?}", &x as *const i32);
println!("y -> {:?}", &y as *const i16);
println!("z -> {:?}", &z as *const i32);
}
/*
output:
x -> 0x7ffc4323fbd4
y -> 0x7ffc4323fbda
z -> 0x7ffc4323fbdc
*/
C:
#include <stdio.h>
int main() {
int x = 0;
short int y = 0;
int z = 0;
printf("x -> %p\
", &x);
printf("y -> %p
", &y);
printf("z -> %p
", &z);
return 0;
}
/*
output:
x -> 0x7ffcac2be03c
y -> 0x7ffcac2be03a
z -> 0x7ffcac2be034
*/
From these pointers, this is the memory layout diagram I drew:
Rust vs. C stack memory padding
Why is this?