1

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 Answer 1

1
  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.

Sign up to request clarification or add additional context in comments.

2 Comments

For #2, I meant for example calling aligned_alloc to allocate instead of malloc, and then in the allocate function, you would manually align the memory to return.
Also, I'm aligning for performance, as I will be doing many allocations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.