Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is comparing pointers across allocations well-defined in Rust?

I have a pointer buf: *const T pointing to the start of an allocation of n elements of T, and I define the following check:

let in_alloc = buf <= ptr && ptr < unsafe { buf.add(n) };

Is it guaranteed that in_alloc is true for any ptr that lies in the allocation of buf, and false in any other case? We may assume that ptr is a valid pointer to a T object (so not misaligned/null/dangling), however it may or may not be from the same allocation as buf. Finally we may assume T is not zero-sized.

like image 850
orlp Avatar asked Mar 15 '26 23:03

orlp


1 Answers

Answering the title, comparing any two pointers is well-defined since pointers implement Ord.

With pointers being totally ordered, the body of the question follows easily from this. You have a set of n distinct pointers, starting at buf + 0 and ending at buf + (n - 1). If ptr is less than buf it can't be equal to any of them. If ptr is greater than buf + (n - 1) it also cannot be equal to them. If ptr is one of them, both expressions evaluate to true.

You can somewhat sidestep the issue and use Range instead:

let end = unsafe { buf.add(n) };
let in_alloc = (buf..end).contains(ptr);

This is often used, for example, to check if a slice contains a pointer.

like image 149
GManNickG Avatar answered Mar 17 '26 16:03

GManNickG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!