NVIDIA Interview Question
Software Engineer / DevelopersI made a code to run on Win32 and align by 8-16-64 bytes.
You can replace LocalAlloc, LocalFree with any counterparts.
//
// Allocates and returns pointer aligned to requested boundary
//
void* AlignedAlloc( size_t cbSize, size_t cbAlign )
{
//
// Align Align-1 ~(Align-1)
// 8 00001000 00000111 11111000
// 16 00010000 00001111 11110000
// 32 00100000 00011111 11100000
// 64 01000000 00111111 11000000
// 128 10000000 01111111 10000000
void *p;
void *ap;
size_t cbExtra = cbAlign+sizeof(void*);
p = LocalAlloc( NONZEROLPTR, cbExtra + cbSize);
ap = (BYTE*) ((size_t)p & ~(cbAlign-1)) + cbAlign;
*((void**)ap-1) = p;
_ASSERT( 0 == (size_t)ap % cbAlign );
return ap;
}
void AlignedFree( void* p)
{
LocalFree( *((void**)p-1) );
}
BTW, is it phone interview or onsite??
- sai February 27, 2011/* align_size has to be a power of two !! */
void *aligned_malloc(size_t size, size_t align_size)
{
char *ptr,*ptr2,*aligned_ptr;
unsigned int align_mask = (unsigned int)align_size - 1;
/* We need to use malloc provided by C. First we need to allocate memory
of size bytes + alignment + sizeof(void *). We need 'bytes' because
user requested it. We need to add 'alignment' because malloc can give us
any address and we need to find multiple of 'alignment', so at maximum multiple
of alignment will be 'alignment' bytes away from any location. We need
'sizeof(void *)' for implementing 'aligned_free', since we are returning modified
memory pointer, not given by malloc ,to the user, we must free the memory
allocated by malloc not anything else. So I am storing address given by malloc just above
pointer returning to user. Thats why I need extra space to store that address.
Then I am checking for error returned by malloc, if it returns NULL then
aligned_malloc will fail and return NULL.
*/
ptr = (char *)malloc(size + align_size + sizeof(void *));
if(ptr == NULL) return(NULL);
ptr2 = ptr + sizeof(void *);
aligned_ptr = ptr2 + (align_size - ((unsigned int)ptr2 & align_mask));
ptr2 = aligned_ptr - sizeof(void *);
*((int *)ptr2)=(int)(ptr);
return(aligned_ptr);
}