I found two simple and sufficient ways to align pointers. Extended discussion can be found here. Here they are:
void* allocate_align_1(size_t size, uintptr_t align)
{
void* addr = malloc(size + align);
uintptr_t aligned_addr = (uintptr_t)addr;
aligned_addr += align - (aligned_addr % align);
return (void*)aligned_addr;
}
void* allocate_align_2(size_t size, uintptr_t align)
{
void* addr = malloc(size + align);
uintptr_t aligned_addr = (uintptr_t)addr;
aligned_addr = (aligned_addr + (align - 1)) & -align;
return (void*)aligned_addr;
}
Link on coliru.
My question is how deallocate_align(void* addr, uintptr_t align)
function can be implemented?
Can pointer which was returned by malloc
be restored from addr
and align align
? Then it should just be passed to free
.