This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: cast lvalues optimizing and strict-aliasing
- From: Ian Lance Taylor <iant at google dot com>
- To: Christian BRUEL <christian dot bruel at st dot com>
- Cc: gcc-help at gcc dot gnu dot org
- Date: Wed, 22 Jul 2009 17:06:33 -0700
- Subject: Re: cast lvalues optimizing and strict-aliasing
- References: <4A66CF6F.70102@st.com>
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