This is the mail archive of the gcc-help@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]

Re: cast lvalues optimizing and strict-aliasing


Christian BRUEL <christian.bruel@st.com> writes:

> From my understanding of the type-punning aliasing rule, the
> following 
> code is correct, and indeed compiles fine with gcc/trunk :
>
> typedef struct {
>   short a : 16;
>   short b : 16;
> } c;
>
> foo(c t1)
> {
>   char *pt1 = (char*)&t1;
>
>   if (*(int*)(pt1))
>     return 0;
>
>   return 1;
> }

No, this is not OK in C.  The rule is that you may access a stored value
only via a union, or a pointer to a compatible type, or a pointer to a
character type.  You You are (presumably) storing the value as short,
and are accessing it as int.  That is not OK.  The rule is about how you
access the value; passing the address of the value through a char *
pointer does not sanitize it.

gcc's aliasing warnings do their best but they are not intended to catch
every erroneous case.


> However if I try to rewrite it using an intermediate cast :
>
> foo(c t1)
> {
>   if (*((int*)((char*)&t1)))
>     return 0;
>
>   return 1;
> }

This isn't OK either.

Ian


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