Allocating aligned address and freeing them
uintptr_t mask = ~(uintptr_t)(align - 1);
void *mem = malloc(1024+align-1);
void *ptr = (void *)(((uintptr_t)mem+align-1) & ~mask);
ptr is the aligned address.
Some time back I faced an interview , There I was asked to write a custom malloc using c malloc
and free
program for a predefined aligned address.
Here is the solution.
The byte before the aligned byte is always empty. We will keep the offset of actual memory allocated by malloc
. But there we have to allocate total memory =(desired+alignment) instead of (desired+alignment-1) downside is that it can store upto 2pow8 offsets.
mallocX(size_t X,alignment Y) {
p= malloc(X+Y);
ret = (p+Y) & ~(Y-1);
*(ret-1) = ret - p;
return ret;
}
similarly for free
freeX(memptr mem) {
free (mem - *(mem-1));
}