pointers-memory · intermediate · ~15 min

Memory alignment pointer arithmetic

Perform power-of-two pointer alignment calculations used in low-level memory allocators.

Challenge

In low-level allocators and hardware DMA buffers, pointers must be aligned forward to a power-of-two byte boundary (e.g. 4, 8, 16, 64 bytes).

Your Task

Implement:

uintptr_t align_forward(uintptr_t addr, size_t align);

Compute the smallest address >= addr that is an integer multiple of align.

Rules

  1. align must be a non-zero power of two (e.g. 1, 2, 4, 8, 16...). If align == 0 or not a power of two, return 0.
  2. Compute the aligned address using bitwise operations: (addr + align - 1) & ~(align - 1).
  3. If addr is already a multiple of align, return addr unchanged.

Example

align_forward(1001, 8);  // returns 1008
align_forward(1024, 16); // returns 1024 (already aligned)
align_forward(1005, 7);  // returns 0 (7 is not a power of two)

Input format

addr: integer address; align: alignment requirement.

Output format

Returns aligned uintptr_t address, or 0 if align is invalid.

Constraints

C11 freestanding. Powers of two only. Bitwise alignment math.

Starter code

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

/* Round addr up to the next multiple of align (must be a power of two).
   Return 0 if align is 0 or not a power of two. */
uintptr_t align_forward(uintptr_t addr, size_t align) {
    (void)addr; (void)align;
    return 0;
}

Common mistakes

Using modulo arithmetic instead of bitwise masking; failing to check if align is a power of two.

Edge cases to handle

align == 0 returns 0; align == 1 returns addr; addr == 0 returns 0; non-power-of-two align returns 0.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.