Riko Ophorst
Riko Ophorst

Reputation: 109

Why do alignments greater than 128 act weird?

So I have been busy trying to write my own custom memory allocators, but I ran into some odd behaviour which I don't understand.

Consider this code:

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

This is supposed to take a pointer and an alignment requirement, and modify the pointer so that it is aligned properly in a forward (positive) direction.

However, when I test this out like so:

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;

The output I get is this:

0
0
1280
1280
1248

That doesn't seem right. It should be:

1536
1280
1280
1280
1248

What is going wrong here?

Upvotes: 0

Views: 69

Answers (1)

rici
rici

Reputation: 241701

Your alignment parameter is uint8_t. What's the value of uint8_t(256)?

Upvotes: 5

Related Questions