Technically, subtracting a null pointer is undefined behaviour in C. Clang 13 issues a warning for it.
Yet this construct is used anyway, usually to determine the alignment of a pointer. For example, BSD-derived implementations of qsort
use it. See here (OpenBSD) and an explanation of what it's for:
Snippet of a code sample with null pointer subtraction from OpenBSD. Please see the link above for full context.
#define TYPE_ALIGNED(TYPE, a, es) \
(((char *)a - (char *)0) % sizeof(TYPE) == 0 && es % sizeof(TYPE) == 0)
Question: Is such code safe to use on typical modern platforms (64-bit or 32-bit) with typical modern compilers? A lot of prominent production code seemed to have used this construct for many years.
I notice that code like this was removed from FreeBSD's qsort
(see revision 334928), because GCC miscompiled some of it. However, I do not understand all the details in the discussion of the issue, and I cannot tell if the problem was a direct consequence of the null pointer subtraction. However, their proposed fix essentially eliminates the null pointer subtraction. I would appreciate some clarifications on the topic.