gcc (6.3.1 20170109) when compiling the following program
#include <stdio.h>
int main(int argc, const char *argv[]) {
unsigned char x[] = {0x66, 0x19};
printf("%i\n", ((short *)((char *)&x[0]))[0]);
return 0;
}
generates as warning:
pun.c: In function ‘main’: pun.c:5:5: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
Shouldn't type aliasing allowed when using char
pointers?
Here’s what C11 (or at least the free draft N1570) has to say about aliasing:
The character type exception means you can access any type via a
char*
orunsigned char*
, but it doesn’t mean you can access achar*
via any type.short*
doesn’t meet the other criteria listed here forchar*
, so this use is undefined behaviour.Plus, you could break alignment requirements if that were allowed unconditionally: