Strict aliasing-related bug even with optimizations disabled
Andrew Pinski
pinskia@gmail.com
Sun Mar 18 00:16:00 GMT 2018
On Sat, Mar 17, 2018 at 11:40 AM, Jonathon Reinhart
<jonathon.reinhart@gmail.com> wrote:
> This was originally posted on Stack Overflow:
> https://stackoverflow.com/a/49339771/119527
>
> The following program:
>
> #include <stdio.h>
>
> static void pshort(short val)
> {
> printf("0x%hx ", val);
> }
>
> int main(void)
> {
> short A[] = {1, 2, 3, 4, 5, 6};
>
> #define EXP ((short*)((char*)A + 7))
>
> short *p = EXP;
> short q = *EXP;
>
> pshort(*p);
> pshort(q);
> pshort(*EXP);
> printf("\n");
>
> return 0;
> }
>
> ...when compiled on x86-64 with
>
> gcc -O0 -fno-strict-aliasing -g -Wall -Werror endian.c
>
> ...produces the following unexpected output
>
> 0x500 0x500 0x4
>
> ...on all available versions of GCC, from 4.9 thru 7.3.1.
>
> It appears that GCC is actually generating different code when the
> expression is used directly as an argument, versus when used with
> intermediate variables.
>
> The language lawyers declared that UB is UB. But -fno-strict-aliasing
> seems to be ineffective here, and this feels like a bug.
As mentioned this is the right mailing list for this kind of question.
But this is undefined not due to aliasing but alignment reasons.
short has an alignment requirement of 2 while you made it unaligned.
Thanks,
Andrew
>
> Jonathon Reinhart
More information about the Gcc-bugs
mailing list