gpt4 book ai didi

pointers - 堆对象的堆栈引用

转载 作者:行者123 更新时间:2023-11-29 08:11:39 25 4
gpt4 key购买 nike

在阅读了几篇关于堆和栈(Rust-lang)的文章后,我了解到非原始类型/数据结构通常位于堆上,在栈中留下一个指针,指向特定对象在堆中的地址。

Heap values are referenced by a variable on the stack, which contains the memory address of the object on the heap. [Rust Essentials, Ivo Balbaert]

考虑以下示例:

struct Point {
x: u32,
y: u32,
}

fn main() {
let point = Point { x: 8, y: 16 };

// Is this address the value of the pointer at the stack, which points to
// the point-struct allocated in the heap, or is the printed address the
// heap-object's one?
println!("The struct is located at the address {:p}", &point);
}

在我的例子中,输出是:

The struct is located at the address 0x24fc58

那么,0x24fc58 是堆栈引用指向的值(地址),还是结构实例在堆中分配的直接内存地址?

一些额外的小问题:

  • 这是“原始地址”,还是相对于程序地址空间的地址?
  • 是否可以通过直接传递十六进制地址来初始化指针?
  • 是否可以访问不在程序地址空间中的内存地址?

最佳答案

您的 Point 实际上驻留在堆栈上——没有 Box 或其他结构可以将它放在堆上。

是的,可以(尽管显然不安全)将地址传递给 *ptr(这是一个裸指针)并将其转换为 &ptr – 这是不安全的,因为后者保证是非空的。

因此,当然可能(尽管非常不安全)访问堆外内存,只要底层系统允许您这样做(大多数当前系统可能只会终止您的进程有段错误)。

关于pointers - 堆对象的堆栈引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32360500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com