I was trying to understand raw pointers in rust and how do raw pointers work, i was trying to allocate memory using raw pointers and then print the base address like so:
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)
}
}
}
The test gives a result below: the address is 0x7f8e5b804080 and value is 0
I have two questions?
- Why am i getting a value of 0?? the base address has nothing
- is the base address i'm getting correct or am i doing something wrong here?
- how do get the address of the pointer itself? ive tried a few options like &*val.as_ptr() but not sure if that works