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: sizeof(union) and #pragma pack()


"Dave Trollope, Diane Barrowman" <daveanddiane@kringlecottage.com> 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));


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