For more or less arbitrary values of k, the only way to do it is to
allocate a block that's sure to be large enough (i.e. 2^(k+1)) and pick
off an address within that block that meets your alignment requirements.
For values of k such that 2^k is the alignment of some type (typically
2, 4, 8, or 16 bytes), malloc returns a pointer that's suitably aligned
for any type, so you don't need to do anything special.
Since I have constraint that I have to use malloc in my application and
I also want that once that memory is passed to me I should be able to
free the memory. Thus simply returning the offset will not solve my
purpose as once the application passes the same location to me , I will
pass the location to free and free wouldn't know that it was actually
allocated. See the code below
The problem with the code below is that free does not know how to free
the memory because I pass it the address which malloc didn't return.
The other problem is that lot of memory gets wasted. Is there a way to
overcome such problems?
#define ALIGNMENT_K 3
void * allocate_memory(size_t size)
{
//allocate memory so that at least there is an address which is
2^k aligned
char * mem = (char *)malloc(size + 2^ALIGNMENT_K);
//calculate offset and if it is not 2^k aligned then
//increment the pointer till it is.
while( (*mem & ~(0xffffffff << ALIGNMENT_K)) != 0 )
{
mem++;
}
return (void *)mem;
}
//If the mem pointer is not the same that malloc returned then it
//is a problem and free won't be able to free the memory
void free_memory(void * mem)
{
free(mem);
}
I hope I am clear in my question and intent.
Thanks,
Divick