vendredi 27 janvier 2017

How is alignment related to the number of trailing zeros in a pointer?

I am trying to understand how memory alignment works in C++.

If I understand it correctly, if n is the number of trailing zeros in the binary representation of a pointer, then the pointer is aligned to 2^n bytes. However, the following program:

#include <bitset>
#include <cstdint>
#include <iostream>

template <typename T>
std::size_t nTrailingZeros(const T* pointer)
{
    std::bitset<sizeof(std::uintptr_t)> bits(reinterpret_cast<std::uintptr_t>(pointer));
    std::size_t nZeroes{};
    while (nZeroes < bits.size() && !bits[nZeroes])
    {
        ++nZeroes;
    }
    return nZeroes;
}

struct alignas(64) A {int x;};

int main()
{
    std::cout << "Alignment: "      << alignof (A)            << std::endl;
    std::cout << "Trailing zeros: " << nTrailingZeros (new A) << std::endl;
} 

Outputs:

Alignment: 64 Trailing zeros: 4

On my computer.

What am I doing wrong? I would expect at least 6 trailing zeros, but I am getting only 4 (suggesting a 16 byte alignment).

Aucun commentaire:

Enregistrer un commentaire