Custom Search

Tuesday, January 29, 2008

Alignment

Sometimes when we are coding on architectures with limited memory footprints , we might end up writing a memory allocator ourselves (more often than not ). Having said that - one of the important design considerations for a memory allocator is getting an address that is probably aligned with the underlying architecture.

Here is the simple code fragment to do the alignment for a given size.
Note that - the align function returns a new address only when the input address is not aligned by itself.


#include <stdlib.h>
#include <stdio.h>

/* align address to be a multiple of n. */
void* align(void* memory, int alignment)
{
unsigned char* ptr;
unsigned int offset;

ptr =(unsigned char*)memory;
offset =(unsigned int)ptr % alignment;

return offset ? (ptr + alignment - offset ): ptr;
}



int main()
{
void * a;

a = malloc(sizeof(char) * 10);

printf("\nAddress: 0x%p ", a );
printf("\nAligned Address:0x%p ", align(a, sizeof(int) ));
return EXIT_SUCCESS;
}




Reblog this post [with Zemanta]

No comments: