pointers-memory · intermediate · ~15 min
Perform power-of-two pointer alignment calculations used in low-level memory allocators.
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).
Implement:
uintptr_t align_forward(uintptr_t addr, size_t align);
Compute the smallest address >= addr that is an integer multiple of align.
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.(addr + align - 1) & ~(align - 1).addr is already a multiple of align, return addr unchanged.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)
addr: integer address; align: alignment requirement.
Returns aligned uintptr_t address, or 0 if align is invalid.
C11 freestanding. Powers of two only. Bitwise alignment math.
#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;
}
Using modulo arithmetic instead of bitwise masking; failing to check if align is a power of two.
align == 0 returns 0; align == 1 returns addr; addr == 0 returns 0; non-power-of-two align returns 0.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.