</>EmbeddedInterview

Allocate memory without malloc or calloc, aligned to 64 bytes

MediumPointers & Memory

You can allocate memory without malloc() or calloc() using a static buffer and align its starting address to a 64-byte boundary using bitwise operations.

Method 1: Using bitwise operators (Interview approach)

#include <stdio.h>
#include <stdint.h>

#define SIZE 1024
#define ALIGNMENT 64

static uint8_t buffer[SIZE + ALIGNMENT - 1];

int main()
{
    uintptr_t addr = (uintptr_t)buffer;

    addr = (addr + ALIGNMENT - 1) & ~(uintptr_t)(ALIGNMENT - 1);

    uint8_t *ptr = (uint8_t *)addr;

    printf("Original address: %p\n", (void *)buffer);
    printf("Aligned address:  %p\n", (void *)ptr);
    printf("Is aligned: %d\n", !(addr & 63));

    return 0;
}

Now ptr points to a 64-byte aligned memory region with at least 1024 usable bytes.

The formula for rounding an address up to an alignment boundary is:

aligned_addr = (addr + 63) & ~(uintptr_t)63;

Suppose the original address is 0x1004.

Original address = 0x1004
Add 63           = 0x1043
Clear last 6 bits
Aligned address  = 0x1040

Why allocate 63 extra bytes?

In the worst case, we may need to skip 63 bytes to reach the next 64-byte aligned address. The additional memory guarantees that 1024 usable bytes remain available.

Method 2: Using C11 _Alignas

#include <stdint.h>

_Alignas(64) static uint8_t buffer[1024];

The compiler ensures 64-byte alignment if that alignment is supported.

Method 3: Using GCC compiler attributes

static uint8_t buffer[1024]
    __attribute__((aligned(64)));
Feature Bitwise _Alignas GCC attribute
Uses malloc/calloc No No No
Extra buffer bytes 63 None required None required
Standard C Yes* C11 onwards No
Runtime alignment calculation Yes No No
Suitable for embedded systems Yes Yes Yes

*The bitwise method assumes a conventional flat address space with uintptr_t support and no address overflow.

For interviews, explain Method 1 first, as it demonstrates your understanding of memory allocation, pointer arithmetic, padding and bitwise manipulation. Then mention compiler-supported alternatives.

Time complexity: O(1).