From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 1430 invoked by alias); 30 May 2011 12:00:08 -0000 Received: (qmail 1415 invoked by uid 22791); 30 May 2011 12:00:06 -0000 X-SWARE-Spam-Status: No, hits=-2.4 required=5.0 tests=AWL,BAYES_00,DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,FREEMAIL_FROM,RCVD_IN_DNSWL_LOW,RFC_ABUSE_POST,T_TO_NO_BRKTS_FREEMAIL X-Spam-Check-By: sourceware.org Received: from mail-pv0-f175.google.com (HELO mail-pv0-f175.google.com) (74.125.83.175) by sourceware.org (qpsmtpd/0.43rc1) with ESMTP; Mon, 30 May 2011 11:59:52 +0000 Received: by pvc30 with SMTP id 30so1683334pvc.20 for ; Mon, 30 May 2011 04:59:51 -0700 (PDT) MIME-Version: 1.0 Received: by 10.68.31.34 with SMTP id x2mr2128036pbh.153.1306756791484; Mon, 30 May 2011 04:59:51 -0700 (PDT) Received: by 10.68.47.67 with HTTP; Mon, 30 May 2011 04:59:51 -0700 (PDT) In-Reply-To: References: Date: Mon, 30 May 2011 12:40:00 -0000 Message-ID: Subject: Re: Weird strict-aliasing break From: Steffen Dettmer To: gcc-help@gcc.gnu.org Content-Type: text/plain; charset=windows-1252 Content-Transfer-Encoding: quoted-printable Mailing-List: contact gcc-help-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Id: List-Archive: List-Post: List-Help: Sender: gcc-help-owner@gcc.gnu.org X-SW-Source: 2011-05/txt/msg00419.txt.bz2 On Mon, May 30, 2011 Thibault Castel wrote: > I have a weird warning when compiling my program with g++: > =A0 "dereferencing pointer =91NAME=92 does break strict-aliasing rules" > > So, I tried to investigate a little bit and find some clues : I do a > memory mapping from a char buffer to a C struct to have access to > different datas into the buffer. Pretty casual. But, when I try to > access one of my inner field, the warning triggers... Huh... Beside that this may have other disadvantages, such as depending on byte order, padding and alighnment issues, in general you cannot assume that constructions like: struct s { int a; // or int32_t }; char buffer[]; struct s *p =3D buffer; p->a; struct s *p =3D buffer+1; p->a; this even may crash (we had such problems on some ARM CPUs). I think better here is using memcpy, but still "you have to know what you are doing". I think the only 100% correct way is proper deserialisation, maybe this way: struct s *p =3D new struct s; p->a =3D (int)(buffer[0]) * 0x1000000 + (int)(buffer[1]) * 0x0010000 + (int)(buffer[2]) * 0x0000100 + (int)(buffer[3]); A better workaround for the alignment probably could be something like: struct s { int a; // or int32_t }; char buffer[]; union x { struct s; char buffer[1]; } > I successfully avoid the warning with "__attribute__((__may_alias__))" > but this "cheat" bother me because : - you might have a case where it breaks things (such as optimization changes behavior) I hope some expert corrects me where I'm wrong. oki, Steffen