How to check a pointer is within a slice of allocated memory

⚓ Rust    📅 2026-03-23    👤 surdeus    👁️ 2      

surdeus

I am trying to check whether a pointer being deallocated is within a slice of memory. Currently I am using ptr::addr, which I think is likely to work ok ( and it seems to work ok ), but I am not quite sure it is definitely right. Snippets of code from here:

struct Block(NonNull<[u8]>);

impl Block {
    fn new(bsize: usize) -> Self {
        let lay = Layout::array::<u8>(bsize).unwrap();
        let p = Global::allocate(&Global, lay).unwrap();
        Self(p)
    }
    fn contains(&self, addr: usize) -> bool {
        let start = self.0.as_ptr().addr();
        addr >= start && addr <= start + self.0.len()
    }
}

and

    fn deallocate(&mut self, p: NonNull<u8>, _lay: Layout) {
        let a = p.addr().get();
        if !self.cur.contains(a) && !self.overflow_contains(a) {
            println!("Bad deallocate, aborting");
            std::process::abort();
        }

Do you think this is ok?

8 posts - 4 participants

Read full topic

🏷️ Rust_feed