Search topics...

How do you determine if a memory address is aligned on a 4 byte boundary in C?

0 upvotes
Practice with AISoon

An address is 4-byte aligned when it is a multiple of 4, i.e. its two least-significant bits are zero. Cast the pointer to uintptr_t (the integer type guaranteed to hold a pointer, from <stdint.h>) and mask off the low bits:

c
#include <stdint.h>
#include <stdbool.h>
static inline bool is_aligned_4(const void *ptr) {
return ((uintptr_t)ptr & 0x3u) == 0u;
}

& 0x3 keeps bits 0–1; if both are zero the address divides evenly by 4. This is faster than ((uintptr_t)ptr % 4) == 0 (though a good compiler optimizes the modulo to the same AND, since 4 is a power of two).

To generalize to any power-of-two alignment A:

c
#include <stdint.h>
#include <stdbool.h>
static inline bool is_aligned(const void *ptr, uintptr_t align) {
/* align must be a power of two */
return ((uintptr_t)ptr & (align - 1u)) == 0u;
}

Notes:

  • Use uintptr_t, not int or long — only uintptr_t/intptr_t are guaranteed wide enough to round-trip a pointer.
  • In C11 you can also query a type's required alignment with _Alignof(type) and request alignment with _Alignas.
  • Checking/forcing alignment matters because unaligned accesses fault (bus/usage fault) on many MCUs (e.g. for LDM/STM, or any access on strict-alignment cores) and are slower even where allowed; DMA engines and cache lines frequently require specific alignment too.