I've learned a little about alignment recently but I am not certain in which situations it will be an issue or not. There are two cases that I wonder about:
The first one is when using arrays:
struct Foo {
char data[3]; // size is 3, my arch is 64-bit (8 bytes)
};
Foo array[4]; // total memory is 3 * 4 = 12 bytes.
// will this be padded to 16?
void testArray() {
Foo foo1 = array[0];
Foo foo2 = array[1]; // is foo2 pointing to a non-aligned location?
// should one expect issues here?
}
The second case is when using a memory pool:
struct Pool {
Pool(std::size_t size = 256) : data(size), used(0), freed(0) { }
template<class T>
T * allocate() {
T * result = reinterpret_cast<T*>(&data[used]);
used += sizeof(T);
return result;
}
template<class T>
void deallocate(T * ptr) {
freed += sizeof(T);
if (freed == used) {
used = freed = 0;
}
}
std::vector<char> data;
std::size_t used;
std::size_t freed;
};
void testPool() {
Pool pool;
Foo * foo1 = pool.allocate<Foo>(); // points to data[0]
Foo * foo2 = pool.allocate<Foo>(); // points to data[3],
// alignment issue here?
pool.deallocate(foo2);
pool.deallocate(foo1);
}
My questions are:
- Are there any alignment issues in the two code samples?
- If yes, then how can they be fixed?
- Where can I learn more about this?
Update
I am using a 64-bit Intel i7 processor with Darwin GCC. But I also use Linux, Windows (VC2008) for 32-bit and 64-bit systems.
Update 2
Pool now uses a vector instead of array.