为什么第二个变量的地址紧跟在第一个变量之后?

时间:2019-07-10 14:46:13

标签: memory-management rust memory-layout

我知道在64位系统上,Vec将存储一个指向堆的8字节指针,8个字节的容量和8个字节的长度。

我假设a的地址紧靠v的地址,但是当我检查堆栈上向量分配的边界时,我发现它总是占用31字节的堆栈内存,超出应有的7个字节。字符串也一样。

pub fn main() {
    let v = vec![1_u8];
    let a = 1_u8;

    let v_raw = &v as *const _;
    let a_raw = &a as *const _;

    println!("v addr = {:p}, dec = {}", v_raw, v_raw as usize);
    println!("a addr = {:p}, dec = {}", a_raw, a_raw as usize);
    println!("offset = {} bytes", a_raw as usize - v_raw as usize);

    // changing below 3 print will affect the mysterious 7 bytes
    //    println!("v_raw addr = {:p}", &v_raw);     // (1)
    //    println!("a_raw addr = {:p}", &a_raw);     // (2)
    println!("v as_ptr = {:p}", v.as_ptr()); // (3)

    // dereference through offset 24 to 30 -> 7 bytes
    let mut offset = 24_usize;
    loop {
        if offset == 31 {
            break;
        }

        // usize to *const usize(raw pointer)
        let mut addr = (v_raw as usize + offset) as *const usize;
        let deref_value = unsafe { *addr as u8 };

        println!(
            "offset = {}, addr = {:p}, value hex = {:x}, value = {}",
            offset, addr, deref_value, deref_value
        );

        offset += 1;
    }
}
v addr = 0x7fffbcf48b70, dec = 140736363531120
a addr = 0x7fffbcf48b8f, dec = 140736363531151
offset = 31 bytes
v as_ptr = 0x55d9c823ea40
offset = 24, addr = 0x7fffbcf48b88, value hex = 0, value = 0
offset = 25, addr = 0x7fffbcf48b89, value hex = 0, value = 0
offset = 26, addr = 0x7fffbcf48b8a, value hex = 0, value = 0
offset = 27, addr = 0x7fffbcf48b8b, value hex = 0, value = 0
offset = 28, addr = 0x7fffbcf48b8c, value hex = 0, value = 0
offset = 29, addr = 0x7fffbcf48b8d, value hex = 0, value = 0
offset = 30, addr = 0x7fffbcf48b8e, value hex = 0, value = 0

有时这7个额外地址包含所有0值,如果我取消注释所有标记为(1)(2)(3)的println!宏,有时则不包含

当我依次声明va时,我期望a在栈上v的旁边,所以为什么还要额外获得这7个字节?这个额外的内存是为特殊目的设计的吗?

1 个答案:

答案 0 :(得分:2)

  

我假设a的地址就在v的地址之后。

仅因为您按此顺序编写了这些变量并不意味着Rust会将它们连续存储在堆栈中。 Rust编译器可以随意在合适的地方将其放置在内存中,而您绝对不能依赖其顺序。最终顺序可能会有所不同,具体取决于:

  • Rust编译器的版本
  • 如果要进行调试或发布编译
  • 目标操作系统
  • 目标CPU架构
  • 应用程序附近的其他代码

Vec的实际大小可以显示为24:

let v = vec![1_u8];
println!("size = {}", std::mem::size_of_val(&v)); // size = 24

另请参阅: