在阅读了几篇关于 The Heap and the Stack (Rust-lang)的文章后,我了解到非原始类型/数据结构通常位于堆上,在堆栈中留下一个指针,指向特定对象在堆中的地址 .
堆值由堆栈上的变量引用,该变量包含堆上对象的内存地址 . [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);
}
就我而言,输出是:
结构位于地址0x24fc58
那么, 0x24fc58 是堆栈引用指向的值(地址),还是在堆中分配struct-instance的直接内存地址?
一些额外的小问题:
-
这是"raw-address",还是相对于程序地址空间的地址?
-
是否可以通过直接传递十六进制地址来初始化指针?
-
是否可以访问不包含地址空间的内存地址?
1 回答
你的
Point
实际上驻留在堆栈上 - 没有Box
或其他结构将它放在堆上 .是的,有可能(虽然显然不安全)将地址传递给
*ptr
(这是一个裸指针)并将其转换为&ptr
- 这是不安全的,因为后者保证是非空的 .因此,当然可以(尽管非常不安全)访问堆外内存,只要底层系统允许您这样做(大多数当前系统可能只是通过分段错误来终止您的进程) .