我试图理解rust中的原始指针以及原始指针是如何工作的,我试图使用原始指针分配内存,然后像这样打印基地址:
pub struct Allocator {
heap_start: NonNull<u8>,
size: usize
}
impl Allocator {
unsafe fn init(size: usize) -> Result<Allocator, LayoutError>{
let layout = std::alloc::Layout::from_size_align(size, size)?;
let heap = NonNull::new(std::alloc::alloc(layout)).unwrap();
Ok(Allocator {
heap_start: heap,
size,
})
}
}
and the test below
#[test]
fn test_alloc_init() {
match unsafe { Allocator::init(64) } {
Ok(alloc) => unsafe {
let val = alloc.heap_start;
println!("the address is {:?} and value is {:?}", val.as_ptr(), *val.as_ptr());
},
Err(erro) => {
assert!(false)
}
}
}
测试结果如下:地址为0x7f8e5b804080,值为0
我有两个问题?
- 为什么我得到的值为0??基地址没有任何内容
- 我的基本地址是正确的,还是我在这里做错了什么
- 如何获取指针本身的地址?我尝试了一些选择,比如&val.as_ptr((,但不确定是否有效
-
分配器可能会重置内存。读取未初始化的内存是UB,所以不应该这样做。
-
看起来是这样?
-
使用地址为
val
:的:p
格式选项
println!("val's address is {:p}", &val);
您也可以使用val
本身:
println!(
"the address is {val:p} and value is {:?}",
*val.as_ptr()
);
或者您可以强制转换为原始指针:
println!("val's address is {:?}", &val as *const _);