3 ms·
> Converting to uintprt_t will give you some result -- but that result won't be useful. Unless you're writing low-level system code, don't do any pointer compar
by cesarb 11y ago
> Converting to uintprt_t will give you some result -- but that result won't be useful. Unless you're writing low-level system code, don't do any pointer comparison or arithmetic unless both pointers point into or just past the end of the same object.
I disagree. There are situations where you need an ordering between unrelated objects, but the precise order doesn't matter, only that it's consistent.
An example is when you have a complex data structure with one lock per node, and you need to lock more than one node at a time for some algorithm.
To prevent a deadlock, you must always take the locks in the same order. Comparing the address of the locks gives you a total order over all the locks, which is enough.
- zodiac 11y agoI think comparing (using <) pointers to unrelated objects is undefined behavior. So you do not get a consistent ordering.
- cesarb 11y agoThe part I quoted is talking about casting the pointers to uintptr_t (which is defined behavior) and comparing the resulting uintptr_t (since it's an integer, comparing it is defined behavior). It's not talking about comparing the pointers directly (which is undefined behavior). His argument is that, while defined behavior, "(uintptr_t)ptr_a < (uintptr_t)ptr_b" is useless; I disagree, since it's a well-known trick to prevent AB/BA type deadlocks.