为什么大于 128 的对齐会表现得很奇怪?

Why do alignments greater than 128 act weird?

所以我一直忙着尝试编写自己的自定义内存分配器,但我 运行 遇到了一些我不理解的奇怪行为。

考虑这段代码:

void* PointerUtil::AlignForward(void* address, const uint8_t& alignment)
{
    return (void*)(((uintptr_t)(address) + (uintptr_t)(alignment - 1)) & (uintptr_t)(~(alignment - 1)));
}

这应该采用指针和对齐要求,并修改指针,使其在正向(正)方向上正确对齐。

然而,当我这样测试时:

int address = 1240;

std::cout << (uintptr_t)memory::PointerUtil::AlignForward((void*)((uintptr_t)address), 512) << std::endl;
std::cout << (uintptr_t)memory::PointerUtil::AlignForward((void*)((uintptr_t)address), 256) << std::endl;
std::cout << (uintptr_t)memory::PointerUtil::AlignForward((void*)((uintptr_t)address), 128) << std::endl;
std::cout << (uintptr_t)memory::PointerUtil::AlignForward((void*)((uintptr_t)address), 64) << std::endl;
std::cout << (uintptr_t)memory::PointerUtil::AlignForward((void*)((uintptr_t)address), 32) << std::endl;

我得到的输出是这样的:

0
0
1280
1280
1248

这似乎不对。应该是:

1536
1280
1280
1280
1248

这里出了什么问题?

你的对齐参数是uint8_tuint8_t(256) 的值是多少?