#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
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.
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.
Assuming a 64-bit machine, any instance of struct foo1 will have 8-byte alignment.
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.
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, enum
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With