Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct alignment

Tags:

c

#define MAX_SIZE 8

enum my_enum
{
    VAL1 = 0;
    VAL2,
    VAL3,
    VAL4,
    VAL_MAX
};

struct my_struct
{
  enum my_enum e;
  int  w[MAX_SIZE];
};

Can a layout in such structure cause alignment issues on a target platform? I understand it much depends on a platform, but generally C compiler is allowed to do padding of structures, so for example on 32 bit machine, where 'int' is 32 bit long:

struct my_struct
{
    int w[MAX_SIZE];
}

is aligned (as fas as I understand) so compiler probably won't be doing anything else with its layout, but adding 'enum my_enum' in the structure can poptentially get the structure un-aligned on such machine. Should I be doing anything special to avoid this and should I be avoiding it at all ?

Would be very thankful for clarifications!

Mark

like image 539
Mark Avatar asked Jan 11 '12 18:01

Mark


People also ask

How does struct alignment work?

Memory align (for struct) For struct , other than the alignment need for each individual member, the size of whole struct itself will be aligned to a size divisible by size of largest individual member, by padding at end. e.g if struct's largest member is long then divisible by 8, int then by 4, short then by 2.

What is structure member alignment in C?

Data structure alignment is the way data is arranged and accessed in computer memory. Data alignment and Data structure padding are two different issues but are related to each other and together known as Data Structure alignment.

Are structs 8-byte aligned?

Assuming a 64-bit machine, any instance of struct foo1 will have 8-byte alignment.

What does 4 byte aligned mean?

For instance, in a 32-bit architecture, the data may be aligned if the data is stored in four consecutive bytes and the first byte lies on a 4-byte boundary. Data alignment is the aligning of elements according to their natural alignment.


1 Answers

The answer is no, you don't have to do anything. If adding a field will break alignment, the compiler will apply padding in the appropriate places to realign it.

In your case, enums are likely to be implemented as an int so you wouldn't have this problem in the first place.

A better example would be:

struct my_struct
{
  char ch;
  int  w[MAX_SIZE];
};

In this case, the compiler will likely place 3 bytes of padding after ch to keep w aligned to 4 bytes.

like image 162
Mysticial Avatar answered Sep 22 '22 08:09

Mysticial