Hacker News new | past | comments | ask | show | jobs | submit login

> If we step back from the standard and ask our self does it make sense to compare two pointers which are derived from two completely unrelated objects? The answer is probably always no.

The one big counterexample I can think of is the difference between memcpy and memmove. The latter is supposed to be able to do arithmetic on memory regions, to see if they overlap. Is this article saying that the standard C implementation of memmove is relying on unspecified behavior?




Memmove is frequently cited as an example of a standard library function that can't be implemented using only standard C. It's incorrect, though: the way to do memmove using standard C is to use malloc to allocate a temporary buffer.

But the whole question is not terribly relevant. When memmove is provided as part of the C implementation it can rely on non-portable platform behaviour just fine. There's no rule that you have to implement libc using only standard C facilities.


And how do you implement malloc() in standard C?


Another example of arbitrary pointer comparison I'm familiar with is for resolving lock ordering problems. If I have a big set of locks that I need to take to complete a particular operation, a simple way to prevent deadlocking is to acquire those locks in the order of their pointers.

E.g. if I have three locks I need to take,

  lock_t *a = (lock_t *)0x100;
  lock_t *b = (lock_t *)0x300;
  lock_t *c = (lock_t *)0x200;
then I'll take them in order a, c, b;


If order of locks is important maybe it's worth considering putting them in an array.


Or maybe keeping a global atomic counter, and reading a unique (to the process) value out of it every time you create a mutex?




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: