Raw pointer memory block base address abd value in rust

Viewed 26

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?

  1. Why am i getting a value of 0?? the base address has nothing
  2. is the base address i'm getting correct or am i doing something wrong here?
  3. how do get the address of the pointer itself? ive tried a few options like &*val.as_ptr() but not sure if that works
1 Answers
  1. Probably the allocator resets the memory. Reading uninitialized memory is UB, so you should not do that.

  2. Looks so?

  3. Use the :p format option with the address of val:

println!("val's address is {:p}", &val);

You can also do that with val itself:

println!(
    "the address is {val:p} and value is {:?}",
    *val.as_ptr()
);

Or you can cast to raw pointer:

println!("val's address is {:?}", &val as *const _);
Related