I don't know why the following code works fine, without gcc
errors (-fstrict-aliasing -Wstrict-aliasing=1
).
#include <stdio.h>
int
main(void)
{
char n = 42;
char *p = &n;
int *q = (int *)p;
*q = 10;
printf("%d|%d\n", *p, *q);
return 0;
}
If I follow the strict aliasing rule:
n1570, § 6.5 Expressions
An object shall have its stored value accessed only by an lvalue expression that has one of the following types:
— a type compatible with the effective type of the object,
— a qualified version of a type compatible with the effective type of the object,
— a type that is the signed or unsigned type corresponding to the effective type of the object,
— a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
— an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
— a character type.
But *q
does not have a type compatible with *p
, either a qualified version, either a signed or unsigned type corresponding, either a character type.
So, why is it allowed?
*q
points to a single char's worth of allocated space, you're writingsizeof(int)
's worth of data there. – Matchar
,unsigned char
, orsigned char
: This code does not violate strict aliasing rules due to the last clause. Nevertheless, it has other problems that yield undefined behavior. – cmaster - reinstate monicaint
type. I can't see anything that allows objects of character type to be accessed through anint
lvalue. – md5