Qualcomm Interview Question
Software Engineer / Developersmake alignment = 32
void * aligned_malloc(size_t bytes, size_t alignment)
{
char *ptr,*aptr;
size_t mask= ~(alignment-1);
if( ( (alignment%2) != 0 ) || (alignment==0))
{
printf("Must be power of 2");
exit(0);
}
ptr=(char *)malloc(bytes+alignment+sizeof(size_t)) ;
//allocate memory bytes + potential wastage due to alignment + storage
if (!ptr)
return NULL;
aptr = (char*)(((size_t)(ptr + sizeof(size_t)) & mask) + alignment);
/*find the next alignment boundary, which is the final pointer we will return
_______________________________________
ptr temp aptr
_______________________________________ */
char *temp = aptr - sizeof(size_t);
//Calculated the location where the actual pointer information will be stored
*((int*)temp) = (int) ptr;
printf("Pointer assigned by malloc %x\n",ptr);
printf("Pointer we return %x\n",aptr);
return aptr;
}
shorter code
- Anonymous October 01, 2009void * round_32()
{
char * ptr = new char[some_num];
if(ptr & 0x1F)
{
ptr =(char*) ((int)ptr+(32-((int)ptr%32)));
}
return ptr;
}
====
this is a good one~ thanks