Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory alignment of classes

I´m working on a memory manager using help of the book Game Engine Architecture. At the moment I´m reading about memory alignment (in the book and web) and I´m not sure how the alignment is used correctly for classes. I understand the concept of memory alignment (e.g. a 4 byte data chunk should be located at an address ending with 0x0, 0x4, 0x8 or 0xC) but at the allocateAligned()-function in the book is a comment that says that the alignment has to be power of two. If i have a class that has two int´s and one char, sizeof(classs) tells me, that the class is 12 bytes big. So, would you pass 32 as alignment? Would it not be a waste of memory and maybe lead to fragmentation?
My question is, how do classes have to be aligned correctly, could you explain me it more detailed (what happens if you want to align bigger data chunks, like 121 bytes) and does it make sense for the bigger chunks to be aligned (because the processor fetches only 8 bytes in one call, if I´m informed right)?

like image 717
immerhart Avatar asked Feb 17 '13 19:02

immerhart


1 Answers

The alignment of a type can never be greater than the size of a type. This is because in an array, there can be no padding between elements.

Just as importantly, though, the alignment of a type may be smaller than the size of the type.

Let's consider your class type: it has three members, two 4-byte integers and one 2-byte integer. Let's assume that the alignment of a 4-byte integer is 4 bytes and the alignment of a 2-byte integer is 2 bytes (this is common). In this case, the alignment of your class type is only 4 bytes. It can be located on any 4-byte boundary and each of its members will be correctly aligned.

This is why your class type has two bytes of padding: 12 is evenly divisible by four, but 10 is not. If your class had no padding, its size would only be 10 bytes, and in an array of elements half of the objects would be misaligned.

like image 182
James McNellis Avatar answered Oct 21 '22 05:10

James McNellis