sizeof and allignment on 32bit target

Roman Kellner maillists@gmx.ch
Fri Jul 25 09:04:00 GMT 2003


Hi Eric,

as far as I know gcc uses double-word alignment as default. Therefore your Value3 which only is a short will increase the struct size up the the next value dividable by 4.

If you wish to have 1 byte alignment us the __attribute__ compiler directive and play around with it a little.

//---------------------------------------------------------------------------

#define _ALIGN1_					__attribute__ ((aligned (1)))
#define _ALIGN2_					__attribute__ ((aligned (2)))
#define _ALIGN4_					__attribute__ ((aligned (4)))
#define _PACKED_					__attribute__ ((packed))

typedef struct
{
    unsigned char   sync[ 2 ];
    unsigned char   clss;
    unsigned char   id;
    unsigned short  len;
} _PACKED_ sUbxTgmHeader;

//---------------------------------------------------------------------------

For more details please see the Cynus gcc compilers manual.

Cheers,

Roman


Hello,

Who can tell me why sizeof(Test.Value) gives 12 bytes? I expected 10 bytes.
Due to allignment in my 32bit target (both intel and arm) two bytes are added
before 'Value4', and sizeof(TestStruct) is 16bytes
Here is my test program:

test.cpp:
--------
#include "stdio.h"

int main()
{

   struct TestStruct
   {
      struct
      {
         unsigned long Value1;
         unsigned long Value2;
         unsigned short Value3;
      } Value;
      unsigned long Value4;
   } Test;

   printf("\r\n" "Sizeof Test: %d", sizeof(Test));
   printf("\r\n" "Sizeof Value: %d", sizeof(Test.Value));
   printf("\r\n" "Expected size of Value: 10");
}
----------

target:
intel P3, gcc 3.2 20020927 (prerelease)
 - the target was build under cygwin: 'gcc test.cpp' and tested: './a.exe'.
   result:
-----------
$ ./a.exe

Sizeof Test: 16
Sizeof Value: 12
Expected size of Value: 10
-----------
On my ARM target (gcc 3.3) I detected the same problem.

Eric




More information about the Gcc-help mailing list