For the code snippet below,
int *p = (int *)malloc(10);
int *q = (int *)malloc(10);
ptrdiff_t x = q - p;
printf("Hello World %td", x);
I understand why a compiler might not throw an error for the pointer subtraction as the operation is undefined, not illegal.
What I do not understand however is the reason for not producing any warning for the situation. I've tried VS2017, gcc 7.1.1 and clang so far without any avail.
Stuff I already went through
From, this answer and the cited para 6.5.6 of N1570 it is quite clear that simply subtracting two pointers does not produce any meaningful result.
For pointers to array members the result is the difference of the subscripts of the two array elements
@ N1570 does makes sense, so I am not contesting the legality of the subtraction.
I'm quite sure the compiler understands that p
and q
are not pointers to array members and could easily warn an unsuspecting user about the problem. Why don't they ?
Even if they don't, is there a flag/compiler option for VS, gcc or clang that could catch this potential source of error ?
Neither does gcc -Wall -Wextra
, nor, /Wall
in VS detect this.