On 10/30/13 15:04, Andrew Haley wrote:
On 10/30/2013 11:04 AM, Norbert van Bolhuis wrote:
I don't understand the -Wpacked description from the GCC manual page, it reads:
-Wpacked
Warn if a structure is given the packed attribute, but the packed attribute has no effect on the layout or size of the structure. Such structures may be
mis-aligned for little benefit. For instance, in this
code, the variable "f.x" in "struct bar" will be misaligned even though "struct bar" does not itself have the packed attribute:
struct foo {
int x;
char a, b, c, d;
} __attribute__((packed));
struct bar {
char z;
struct foo f;
};
why does the "__attribute__((packed))" for struct foo cause misalignment for struct bar ?
__attribute__((packed)) is applied piecewise to each member of a packed
struct.
I would expect misalignment only if struct bar is defined with __attribute__((packed))
or its member f.
I thought __attribute__((packed)) only works for (the members of) the struct, but apparently
it tries to avoid 3 bytes extra padding in struct bar. However, sizeof(struct bar) = 12 !?
so there still is 3 bytes padding *and* misalignment. Why would anyone ever want this gcc behaviour ?
Try an array of struct bar.
Andrew.
ok, thanks Andrew, that makes things more clear.
I guess you could say the alignment for (packed) struct foo changes to 1 (so it is placed
like a char in other structs).
unpacked struct bar still aligns on 4 byte boundaries (probably default), this is indeed
desired in an array of struct bar, but also if there is another int member (after member f).
Norbert.