</>EmbeddedInterview

Implement aligned_malloc() and aligned_free().

Medium"Coding: Memory & String Functions"
#include <stdint.h>
#include <stdlib.h>

/* alignment must be a power of two */
void *aligned_malloc(size_t size, size_t alignment)
{
    if (alignment < sizeof(void *) || (alignment & (alignment - 1)) != 0)
        return NULL;
    size_t extra = alignment - 1 + sizeof(void *);       /* room to align + store the original */
    if (size > SIZE_MAX - extra) return NULL;            /* overflow check */
    void *raw = malloc(size + extra);
    if (raw == NULL) return NULL;
    uintptr_t start = (uintptr_t)raw + sizeof(void *);
    uintptr_t aligned = (start + alignment - 1) & ~(uintptr_t)(alignment - 1);
    ((void **)aligned)[-1] = raw;                        /* store original pointer just before */
    return (void *)aligned;
}

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

What the interviewer wants to hear

  1. Allocate size + alignment − 1 + sizeof(void*) bytes.
  2. Skip space for one pointer, then round up to the alignment with (x + a − 1) & ~(a − 1).
  3. Store the original malloc pointer in the word immediately before the aligned address.
  4. aligned_free reads that word and frees the original block.

Follow-ups: why sizeof(void *) extra (so there is always room to store the original pointer, even if malloc already returned an aligned address); why power of two (the mask trick); never pass the aligned pointer to plain free. Standard alternatives: C11 aligned_alloc(alignment, size) (size must be a multiple of the alignment), POSIX posix_memalign. Uses: DMA buffers aligned to cache lines (32/64 bytes), SIMD data (16 bytes), page-aligned buffers (4096).