Check if Pointer is Aligned using C++

Check if Pointer is Aligned using C++

In C++, memory alignment is crucial when dealing with performance-critical applications or low-level optimizations. Misaligned pointers can lead to inefficient memory access and increased CPU cycles. One common scenario where alignment matters is when leveraging SIMD instruction sets, which require data to be aligned to specific memory boundaries for optimal performance. This tutorial provides 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 by converting the pointer to an integer type (uintptr_t) and using the modulo operator (%) to test divisibility by the alignment value. If the address modulo the alignment is zero, the pointer is properly aligned.

#include <iostream>

bool isAligned(const void* ptr, const size_t alignment) {
    return reinterpret_cast<uintptr_t>(ptr) % alignment == 0;
}

int main() {
    float data1[] = {1, 2, 3, 4, 5};
    std::cout << isAligned(data1, 32) << std::endl; // 0 or 1

    alignas(32) float data2[] = {1, 2, 3, 4, 5};
    std::cout << isAligned(data2, 32) << std::endl; // 1

    return 0;
}

The data1 array may or may not be 32-byte aligned depending on how the compiler layout the stack or data section - that's why isAligned(data1, 32) can sometimes output 0 (false) or 1 (true). However, data2 is explicitly aligned using alignas(32), so the result is reliably 1 (true).

Leave a Comment

Cancel reply

Your email address will not be published.