ubsan (-fsanitize=undefined) should detect undefined subtraction of two pointers
Consider:
typedef struct { int x, y; } A;
long f(int* p) { return (A*)(p+1) - (A*)p; }
This has unconditional undefined behavior: the offset between the pointers isn't a multiple of the size of the struct. (This is a part of the general rule that the operands to pointer subtraction must be elements of an array.) The generated IR makes assumptions about this (using "sdiv exact"), but ubsan currently doesn't detect it.
We're adding a flag -fstable-pointer-subtraction that makes this defined (#196392); this is asking for the corresponding check.
Hi @efriedma-quic, this is an interesting subject to work on, let me give it an attempt : )
Created a patch for it, proposing the name unaligned-pointer-subtraction as a new UBSan check.
typedef struct { int x, y; } A; // sizeof(A) == 8
long f(int *p) { return (A *)(p + 1) - (A *)p; } // distance 4, not a multiple of 8
With -fsanitize=unaligned-pointer-subtraction this now reports at runtime:
runtime error: pointer subtraction with byte distance 4 that is not a multiple of the element size 8
Let me know if this is making sense, thanks!