I subtracting two null pointers a UB? Asking for a friend.
@vitaut Am I doing it right sir?
$ cat -p test.c
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
int main()
{
uintptr_t *a = NULL;
uintptr_t *b = NULL;
ptrdiff_t c = a - b;
printf("%td\n", c);
return 0;
}
$ gcc test.c -Wall -Wextra -pedantic -O0
$ ./a.out
0
Gonna push this to master
.
First thing to do is ask at the altar of the conexpr gods: https://godbolt.org/z/67dEq7P4e
next things verify the answer from the one true codex of knowledge: https://eel.is/c++draft/expr.add#5.1
@vitaut it's UB, see C23 (or at least N3220, I don't have the full standard) 6.5.7p10 "When two pointers are subtracted, both shall point to elements of the same array object, or one past
the last element of the array object". Two null pointers don't point to array objects, so subtracting them is UB. IIRC ubsan will list it as UB if it happens.
@oleksandr Code review: return 0 is redundant otherwise LGTM
@palmer @oleksandr not literally NULLs but pointers that are only known at runtime to be null
@yrlf I was also looking at that and was expecting a UB. Maybe there is another piece of wording that makes it not a UB specifically for null pointers.
@vitaut should just result in 0-0 = 0. not really UB. don't we constantly check if (!ptr) everywhere? so a null pointer must be set to zeros or all those nice "checks for null pointers" would be all wrong :)
It is left as an exercise to the reader as to what an appropriate sacrifice for the constexpr gods would be.