On 03/19/2013 05:33 AM, Russell Shaw wrote:
> On 19/03/13 15:30, Shao Miller wrote:
>> On 3/18/2013 21:51, Russell Shaw wrote:
...
>>> I don't quite understand.
>>>
>>> Just declaring:
>>>
>>> struct { char c; int x; } mystruct;
>>>
>>> declares a stack object with suitable size & alignment.
>>>
>>
>> How do you know that there are the same number of padding bytes between these
>> two members as in the original pointer type's referenced type? How do you know
>> the alignment requirement is the same?
>
> The compiler sets the alignment of the struct to match it's worst case member,
> "int".
Not necessarily - the alignment could be stricter. Some systems impose a
minimum alignment for struct types, which could be greater than that for
'int'.
> Because "char c" comes first it'll be aligned as if it were an "int", so there
> will be padding between "c" and "x". ...
Except in those rare cases where sizeof(int)==1.
> ... All object instances of this struct will
> get aligned and padded the same way by the compiler.
There's neither a struct tag nor a typedef name attached to that struct
type; the only way another object could have the same type as mystruct
is by being defined in the same declaration as mystruct. Anywhere else,
a declaration of a different identifier with exactly the same struct
definition would have a different type, and could therefore, in
principle, have different alignment characteristics.
That's extremely unlikely to be the case. First of all, there's no
obvious reason for ever inserting more than the absolute minimum amount
of padding needed to achieve the required alignment. Secondly, identical
struct definitions used in different translation units must be
compatible; it's only when they occur within the same translation unit
that they're incompatible. The easiest way to achieve this is to
implement then identically even when in the same translation unit.
However, in principle, a fully conforming implementation could check
whether a given unnamed struct type is ever used in a way that could
require it to be compatible with a struct type declared in some other
translation unit. If not, it could randomly choose the amount of
padding, constrained only by the requirement that the mystruct and
mystruct.x must both be aligned correctly for 'int'.
If you want to guarantee that two structs not declared in the same
declaration have the same layout, you should name the struct type, with
either a struct tag or a typedef, so you can explicitly declare them to
have the same type. That's what the tag is there for.
--
James Kuyper