Check if Pointer is Aligned using C

Check if Pointer is Aligned using C

In C, memory alignment can be a critical concern - especially when you're working with hardware, SIMD instruction sets, or optimizing for performance. Proper alignment ensures that data is stored and accessed efficiently, while misaligned access can lead to performance penalties. This tutorial provides an example how to check if pointer is aligned using C.

The provided isAligned function checks whether a given pointer is aligned to a specified byte boundary. It does this by casting the pointer to an integer type (uintptr_t) and checking divisibility by the alignment value using the modulo operator (%). If the result equals zero, it means the pointer is properly aligned.

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

_Bool isAligned(const void* ptr, const size_t alignment) {
    return (uintptr_t)ptr % alignment == 0;
}

int main() {
    float data1[] = {1, 2, 3, 4, 5};
    printf("%d\n", isAligned(data1, 32)); // 0 or 1

    _Alignas(32) float data2[] = {1, 2, 3, 4, 5};
    printf("%d\n", isAligned(data2, 32)); // 1

    return 0;
}

The data1 array might not be 32-byte aligned, as its alignment depends on how the compiler arranges memory on the stack - so isAligned(data1, 32) can return either 0 (false) or 1 (true), depending on the situation. In contrast, data2 is explicitly aligned using _Alignas(32), ensuring it is always 32-byte aligned, so isAligned(data2, 32) consistently returns 1 (true).

Leave a Comment

Cancel reply

Your email address will not be published.