Yet another aliasing question.
Sergei Organov
osv@javad.com
Sat Dec 23 10:45:00 GMT 2006
Hello,
I'm trying to understand the implications of strict aliasing rules on
programming practices. I've got two example functions foo() and boo()
that I think both are valid from the POV of strict aliasing
rules. GCC either warns about both (with -Wstrict-aliasing=2) or doesn't
warn about any (with -Wstrict-aliasing), and generates the assembly as
if the functions don't violate the rules.
I'm still in doubt, especially w.r.t. the boo() function. Could anybody
clarify the issue please?
$ cat alias.c
typedef struct { int i; } S;
int i;
int foo()
{
// Accessing object 'i' of type 'int' through 'S' containing 'int'
// field. Should be OK from C99 standard POV?
S const sc = { 10 };
*(S*)&i = sc;
return i;
}
S s;
int boo()
{
// Accessing 's' of type 'S' through 'int'. Is it aliasing rules
// violation? Maybe yes, but on the other hand this could be
// considered as accessing 's.i' of type 'int' through 'int' that
// should be OK from C99 standard POV?
*(int*)&s = 10;
return s.i;
}
$ gcc-4.2 -O3 -W -Wstrict-aliasing=2 -c alias.c -o alias.o
alias.c: In function 'foo':
alias.c:9: warning: dereferencing type-punned pointer might break strict-aliasing rules
alias.c: In function 'boo':
alias.c:19: warning: dereferencing type-punned pointer might break strict-aliasing rules
-- Sergei.
More information about the Gcc-help
mailing list