This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Tricky(?) aliasing question.


Hello,

[I apologize for posting this question here, but I've tried to ask at
gcc-help, got no response, and don't actually know where else to ask]

Below are two example functions foo() and boo(), that I think both are
valid from the POV of strict aliasing rules. GCC 4.2 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.e, both functions return 10.

I'm still in doubt, especially w.r.t. the boo() function. Could anybody
clarify the issue please (see comments in the functions for my own
thoughts)?

$ cat alias.c
typedef struct { int i; } S;

int i;
int foo()
{
  S const sc = { 10 };
  i = 20;
  // Accessing object 'i' of type 'int' through 'S' containing 'int'
  // field.  Should be OK from C99 standard POV?
  *(S*)&i = sc;
  return i;
}

S s;
int boo()
{
  s.i = 20;
  // 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.



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]