Alignment of struct in a linear allocator

Viewed 74

I'm building a very simple linear allocator for this class on x64:

class Test {
    size_t first[64];    // 512 bytes
    void* second[64];    // 512 bytes
    unsigned char third; // 1 byte
};

The total size of Test should be 1025 bytes, but its actual size is 1032 bytes, which is expected. The compiler has automatically aligned the structure, which is good.

Now here is the barebones of what my linear allocator is:

class Allocator {
private:
    Test* memory;
public:
    Allocator(const size_t size) {
        memory = static_cast<Test*>(malloc(sizeof(Test) * size));
    }
    Test* allocate() {
        return memory++;
    }
};

And it works well!

However, I see that many other simple linear allocators align the memory in the allocate function. Why do they do this? The Test structure itself is already aligned.

Also, if you do decide to use some type of alignment, would you align the memory when you allocate it? Or would you return an aligned pointer in the allocate function? Also, would you align it to the sizeof(Test), or the platform's WORD size?

1 Answers
  1. many other simple linear allocators align the memory in the allocate function. Why do they do this? They do it if they need to align differently, for example 16 or 32 bytes (to use with AVX).

  2. if you do align the newly allocated memory, would you align the memory when you allocate it? Or would you align it when you return the memory block? You can't re-align already allocated memory.

  3. Also, would you align it to the sizeof(Test), or the platform's WORD size? Depends on WHY you are aligning.

Related