</>EmbeddedInterview
← All problems · Pointers & Strings

Aligned Allocation

Hard

DMA engines and caches often need buffers aligned to 32 or 64 bytes. Using only malloc and free, write:

  • void *aligned_alloc_x(size_t align, size_t size): returns memory aligned to align (a power of two), or NULL.
  • void aligned_free_x(void *p): frees memory from aligned_alloc_x, and accepts NULL.

Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

Over-allocate by align - 1 bytes plus room for one pointer. Round the address up, and store the original malloc pointer just before the aligned block so free can find it.

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

void *aligned_alloc_x(size_t align, size_t size)
{
    if (align == 0 || (align & (align - 1)) != 0) return NULL;
    if (align < sizeof(void *)) align = sizeof(void *);

    size_t extra = align - 1 + sizeof(void *);
    if (size > SIZE_MAX - extra) return NULL;

    void *raw = malloc(size + extra);
    if (!raw) return NULL;

    uintptr_t p = ((uintptr_t)raw + sizeof(void *) + align - 1) & ~(uintptr_t)(align - 1);
    ((void **)p)[-1] = raw;           /* remember the original pointer */
    return (void *)p;
}

void aligned_free_x(void *p)
{
    if (p) free(((void **)p)[-1]);
}

Reserving sizeof(void *) bytes before rounding up guarantees there is always room for the hidden pointer, and since the alignment is at least pointer size, the hidden pointer slot is itself aligned. The size check prevents integer overflow in size + extra, a common security bug.

C11 provides aligned_alloc(align, size) (size must be a multiple of align) and POSIX provides posix_memalign; the Linux kernel's kmalloc gives natural alignment for power-of-two sizes. For DMA buffers on cached cores, also round the size up to a cache-line multiple so invalidation does not destroy neighbouring data.

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    size_t aligns[] = { 8, 16, 32, 64, 256, 4096 };
    for (size_t i = 0; i < sizeof aligns / sizeof aligns[0]; i++) {
        uint8_t *p = aligned_alloc_x(aligns[i], 100);
        CHECK(p != NULL);
        CHECK(((uintptr_t)p & (aligns[i] - 1)) == 0);
        memset(p, 0xAB, 100);       /* must own all 100 bytes */
        aligned_free_x(p);
    }
    CHECK(aligned_alloc_x(24, 10) == NULL);   /* not a power of two */
    aligned_free_x(NULL);
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}