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]

Re: aliasing warnings


Eduard Hasenleithner <eduard@hasenleithner.at> writes:

> Since gcc 4.4 I get considerably more
> "dereferencing type-punned pointer will break strict-aliasing rules"
> warnings with my code. The code ist used for message en- and de-capsulation.

This question is not appropriate for the mailing list gcc@gcc.gnu.org,
which is for gcc developers.  It would be appropriate for
gcc-help@gcc.gnu.org.  Please take any followups to gcc-help.  Thanks.


This warning will reliably report cases where your code may be
miscompiled.  It does not reliably report all cases where the C/C++
aliasing rules are broken.  We can only report warnings that we can
find, and the warnings are limited by the quality of the alias
analysis done in the compiler.  As the alias analysis gets more
sophisticated, the warnings detects more invalid code.


> struct msg {
>   uint8_t msg_type;
>   uint8_t msg_len;
>   uint8_t msg_data[0];
> };

> struct msg *msg = receive();
> if (msg->msg_type==5 && msg->msg_len==8) {
>   printf("a: %d\n", *(uint32_t*)(msg->msg_data+0));
>   printf("b: %d\n", *(uint32_t*)(msg->msg_data+4));
> }

This looks to me like a pretty clear aliasing violation.  You are
accessing data defined in one type using a different type.  The
difference between the two cases is admittedly rather subtle.
msg->msg_data+0 is accessing the object msg->msg_data which has type
uint8_t[0].  msg->msg_data+4 is already wandering off into unspecified
behaviour, as you are accessing beyond the end of the array (the C99
syntax for a flexible array is msg_data[], not msg_data[0]; I can't
recall whether C++ permits this).  The type of that is uint8_t*.  This
is still an aliasing violation, but evidently one that the compiler
does not detect.

Ian


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