rust - Rust 在哪里存储所有这些字节?

标签 rust

为了理解堆栈内存的工作原理,我编写了以下代码来显示数据存储位置的地址:

fn main() {
    let a = "0123456789abcdef0";
    let b = "123456789abcdef01";
    let c = "23456789abcdef012";

    println!("{:p} {}", &a, a.len());
    println!("{:p} {}", &b, b.len());
    println!("{:p} {}", &c, c.len());
}

输出是:

0x7fff288a5448 17
0x7fff288a5438 17
0x7fff288a5428 17

这意味着所有 17 个字节都存储在 16 个字节的空间中,这是不对的。我的一个猜测是发生了一些优化,但即使我使用 --opt-level 0 进行构建,我也会得到相同的结果。

等效的 C 似乎做了正确的事情:

#include <stdio.h>
#include <string.h>

int main() {
    char a[] = "0123456789abcdef";
    char b[] = "123456789abcdef0";
    char c[] = "23456789abcdef01";

    printf("%p %zu\n", &a, strlen(a) + 1);
    printf("%p %zu\n", &b, strlen(b) + 1);
    printf("%p %zu\n", &c, strlen(c) + 1);

    return 0;
}

输出:

0x7fff5837b440 17
0x7fff5837b420 17
0x7fff5837b400 17

最佳答案

字符串字面量"..."存放在静态内存中,变量a, b, c 只是指向它们的(胖)指针。它们的类型为 &str,其布局如下:

struct StrSlice {
    data: *const u8,
    length: uint
}

data 字段指向构成文本的字节序列,length 字段表示有多少字节。

在 64 位平台上这是 16 字节(在 32 位平台上是 8 字节)。 C 中的真正等效项(忽略空终止与存储长度)将存储到 const char* 而不是 char[],将 C 更改为此打印:

0x7fff21254508 17
0x7fff21254500 17
0x7fff212544f8 17

即指针相隔 8 个字节。

您可以使用 --emit=asm--emit=llvm-ir 检查这些底层细节,或者点击 corresponding button on the playpen(可能调整优化级别)也)。例如

fn main() {
    let a = "0123456789abcdef0";
}

使用 --emit=llvm-ir 编译并且没有优化(使用我的修剪和注释):

%str_slice = type { i8*, i64 }

;; global constant with the string's text
@str1042 = internal constant [17 x i8] c"0123456789abcdef0"

; Function Attrs: uwtable
define internal void @_ZN4main20h55efe3c71b4bb8f4eaaE() unnamed_addr #0 {
entry-block:
  ;; create stack space for the `a` variable
  %a = alloca %str_slice

  ;; get a pointer to the first element of the `a` struct (`data`)...
  %0 = getelementptr inbounds %str_slice* %a, i32 0, i32 0
  ;; ... and store the pointer to the string data in it
  store i8* getelementptr inbounds ([17 x i8]* @str1042, i32 0, i32 0), i8** %0

  ;; get a pointer to the second element of the `a` struct (`length`)...
  %1 = getelementptr inbounds %str_slice* %a, i32 0, i32 1
  ;; ... and store the length of the string (17) in it.
  store i64 17, i64* %1
  ret void
}

关于rust - Rust 在哪里存储所有这些字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25468422/

相关文章:

rust - 匹配对模式的引用或取消引用的值之间有什么区别吗?

json - 无法使用本地创建的向量,因为 "borrowed"

rust - 如何使用serde-json库为包含原始值的结构计算哈希

Rust:如何散列字符串?

rust - 如何从数组值创建实例

rust - 为什么我在子模块中需要 `use` 语句而不是在 main.rs 中?

string - Rust 中的切片和引用之间的关系是什么?

rust - 如何从 Rust 中的不安全内存创建原子

testing - Rust 禁用特定目标的所有测试

linker - 如何提供或删除对 _GLOBAL_OFFSET_TABLE_ 的依赖?