Alignment of Structs – Chaotic Evil

Don’t be tripped up by data alignment. Sometimes in C you want to play with unions and structs or just cast to a char * and stream data, but unless you consider the architecture and the alignment it is almost guaranteed to bite you (editor’s comment: or is that byte you?).

Most (read: all I have tested) compilers word align data based on type so: doubles will on x86 be typically 64bit (sometimes 32bit) aligned, ints 32-bit aligned, shorts 16-bit, chars 8-bit, etc.

So consider these 2 structs:

struct Foo
{
	int a;
	int b;
	char d;
	char e;
} A;

struct Bar
{
	char e;
	int b;
	char d;
	int a;
} B;

Do a sizeof(A) and sizeof(B) and you will find they yield very different results. (i got 12 and 16).

Unfortunately it varies compiler to compiler and architecture to architecture so alignment, sizes and spaces will vary. In the example Foo on x86-32 Windows Borland Builder 5:

a is 4 byte word aligned
b follows straight after a so is by default
d follows straight after b so is by default but doesn’t need to be
e is byte aligned and directly follows d

2 bytes are left at the end as the structure requires more than 2 words and cant get 2.5 words so it gets 3 4-byte words

In the example Bar:

e is 4 byte word aligned as it the start of the structure
b, though e is only 1 byte, is 4 byte aligned for efficient memory access so 3 spare bytes are left between them
d follows straight after b so is by default but doesn’t need to be
a, though d is only 1 byte, is 4 byte aligned for efficient memory access so 3 spare bytes are left between them

We can write our code in an intelligent way bearing this in mind to insure that we don’t waste unnecessary memory and that our code is contiguous (without spaces between items), by putting the largest word aligned types first and then smaller types down to smallest at the end.

By doing this we have ended up with a data structure without gaps (except at the end) like in foo which can be sensibly used in a union or stream.

1 thought on “Alignment of Structs – Chaotic Evil

  1. Pingback: - Shattered Silicon

Leave a Reply

Your email address will not be published. Required fields are marked *