[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.c

union/struct alignment safety

Sean Hamilton

9/5/2011 6:50:00 AM

struct a { uint8_t b, c, d, e; };
union b { uint8_t f[16]; struct a g[4]; };

Is it guaranteed that b.f and b.g will have the same address and size?
Is a struct with only one type of member like that equivalent to an
array with regard to alignment and padding?

Thanks in advance,
2 Answers

Andrey Tarasevich

9/5/2011 7:38:00 AM

0

Sean Hamilton wrote:
> struct a { uint8_t b, c, d, e; };
> union b { uint8_t f[16]; struct a g[4]; };
>
> Is it guaranteed that b.f and b.g will have the same address and size?

The same address is guaranteed. The size is not guaranteed to be the
same. However, it "should" be the same in any reasonable practical
implementation.

> Is a struct with only one type of member like that equivalent to an
> array with regard to alignment and padding?

No, he language make no such guarantee. And again, what will happen in
practice depends on implementation. Normally one should expect the
equivalence of memory layouts for array and struct to hold, unless one
takes specific steps to break that equivalence (like adjust struct field
alignment by implementation-specific means).

--
Best regards,
Andrey Tarasevich

Richard Damon

9/5/2011 3:35:00 PM

0

On 9/5/11 2:49 AM, Sean Hamilton wrote:
> struct a { uint8_t b, c, d, e; };
> union b { uint8_t f[16]; struct a g[4]; };
>
> Is it guaranteed that b.f and b.g will have the same address and size?
> Is a struct with only one type of member like that equivalent to an
> array with regard to alignment and padding?
>
> Thanks in advance,

for union, the address of each member will be the same, that of the
union, no padding before the member is allowed.

The size may not be the same. Structs may have padding, and the compiler
may decide that it is helpful for all structs to have a certain minimal
alignment, which if it was larger than 4, might cause sizeof(struct a)
to be > 4. This is particularly likely on a word addresses machine,
where pointers to individual bytes requires a longer pointer to add byte
offsets, as a pointer to struct needs to have its format defined
independent of the detail of the contents of the struct.

So a Word Addressed machine with 64 bit words, would likely added 4
bytes of padding to struct a.