Course contentsShow
← C
Lesson 589 of 1,2198. Memory ManagementFree lesson

Handling alignment within an arena

Handling alignment within an arena

What you'll learn: How to manually align the "offset" pointer in an arena to ensure the CPU can safely and efficiently access different data types.

The problem: Misalignment

In an arena allocator, you typically have a large char buffer and a size_t offset that tracks where the next allocation starts. If you allocate 5 bytes for a string, your offset moves from 0 to 5. If you then try to allocate a 4-byte int, that integer will start at address 5.

Here is the catch: most CPUs are picky. They want a 4-byte int to start at an address divisible by 4, and an 8-byte double to start at an address divisible by 8. This is called alignment. If you ignore this, your program might crash or run slowly because the CPU has to do extra work to "stitch together" a value that straddles a memory boundary.

The solution: Padding

To fix this, we don't just take the next available byte. We "bump" the offset forward to the next multiple of the required alignment. Think of it like a parking lot where motorcycles take 1 spot, but buses must start at a spot number divisible by 4. If a motorcycle takes spot 0, and a bus arrives, spot 1, 2, and 3 stay empty—the bus starts at spot 4.

Implementing the "Align Forward" logic

We use a bit of math to calculate the padding. While you can use the modulo operator (%), a common industry trick uses bitwise logic for speed.

#include <stdint.h>
#include <stddef.h>

typedef struct {
    unsigned char *buffer;
    size_t size;
    size_t offset;
} Arena;

// Rounds the current offset up to the nearest 'align' boundary
uintptr_t align_forward(uintptr_t address, size_t align) {
    // align must be a power of 2 (2, 4, 8, 16)
    return (address + (align - 1)) & ~(align - 1);
}

void* arena_alloc(Arena *a, size_t size, size_t align) {
    // 1. Calculate the absolute address of the current offset
    uintptr_t current_ptr = (uintptr_t)a->buffer + a->offset;
    
    // 2. Align that address
    uintptr_t aligned_ptr = align_forward(current_ptr, align);
    
    // 3. Calculate new offset relative to the buffer start
    size_t new_offset = aligned_ptr - (uintptr_t)a->buffer + size;
    
    if (new_offset <= a->size) {
        void *ptr = (void *)aligned_ptr;
        a->offset = new_offset;
        return ptr;
    }
    
    return NULL; // Out of memory
}

By passing the alignment requirement (like alignof(int)) to your allocator, you ensure the pointer returned is always "legal" for the data type you intend to store there.

Key takeaway

Alignment ensures data starts at memory addresses the CPU can read efficiently; always "bump" your arena offset to the next valid boundary before carving out a new block.