From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 5004 invoked by alias); 22 Sep 2004 18:46:47 -0000 Mailing-List: contact gcc-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Archive: List-Post: List-Help: Sender: gcc-owner@gcc.gnu.org Received: (qmail 4994 invoked from network); 22 Sep 2004 18:46:46 -0000 Received: from unknown (HELO sccrmhc13.comcast.net) (204.127.202.64) by sourceware.org with SMTP; 22 Sep 2004 18:46:46 -0000 Received: from greed.local (c-67-169-96-182.client.comcast.net[67.169.96.182]) by comcast.net (sccrmhc13) with ESMTP id <2004092218464501600mobafe>; Wed, 22 Sep 2004 18:46:46 +0000 Received: by greed.local (Postfix, from userid 501) id 1384D2E9D9A; Wed, 22 Sep 2004 11:46:46 -0700 (PDT) To: "Dave Trollope, Diane Barrowman" Cc: gcc@gcc.gnu.org Subject: Re: sizeof(union) and #pragma pack() References: <4150C8D5.7070200@nycap.rr.com> <41510C11.6010000@kringlecottage.com> From: Geoffrey Keating Date: Wed, 22 Sep 2004 20:41:00 -0000 In-Reply-To: <41510C11.6010000@kringlecottage.com> Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.2 MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-SW-Source: 2004-09/txt/msg01307.txt.bz2 "Dave Trollope, Diane Barrowman" writes: > Hi, > > The following code seems to cause the sizeof() function to return a > size that is two bytes larger than I expected. Is this the right > behaviour? > > struct a6 { unsigned long a; unsigned short b }; > #pragma pack(2) > struct a10 { > union { > struct a6 emedded; > int *ptr; > } > unsigned long junk; > }; > #pragma pack() > > I was expecting sizeof(struct a10) to return 10 but it returns 12. > > If I move the #pragma pack(2) above the first struct definition, > sizeof(struct a10) returns 10 as expected. This is presumably because > the packing between the structure and the union is miscalculated from > the structure defaulting to a padded 8. > > I'd like to know if this is the expected behaviour, or if this is > something that needs fixing? This is correct. sizeof(struct a6) is 8, and 'int *' is 4, and 8+4=12. This is necessary for correct behaviour if you say, for instance, struct a6 x; struct a10 y; memcpy (&y.emedded, x, sizeof (x));