Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default structure alignment for 32 bit processor word

I'm working with an struct compiled for a 32bit ARM processor.

typedef struct structure {
   short a;
   char b;
   double c;
   int d;
   char e;
}structure_t;

If I use nothing, __attribute__ ((aligned (8))) or__attribute__ ((aligned (4))) I get the same results in terms of structure size and elements offset. Total size is 24. So I think it is always aligning to 8 (offsets are for both a=0 , b=2, c=8, d=16, e=20).

Why is 8 the default alignment chosen by the compiler? Should not it be 4 because is a 32 word processor?

Thanks in advance mates.

like image 470
ferdepe Avatar asked Oct 15 '25 05:10

ferdepe


1 Answers

The aligned attribute only specifies a minimum alignment, not an exact one. From gcc documentation:

The aligned attribute can only increase the alignment; but you can decrease it by specifying packed as well.

And the natural alignment of double is 8 on your platform, so that is what is used.

So to get what you want you need to combine the aligned and packed attributes. With the following code, c has offset 4 (tested using offsetof).

typedef struct structure {
   short a;
   char b;
   __attribute__((aligned(4))) __attribute__((packed)) double c;
   int d;
   char e;
} structure_t;
like image 71
Samuel Peter Avatar answered Oct 16 '25 23:10

Samuel Peter