I\'m trying to allocate a block of memory of size size which needs to be Alignment aligned where the size may not be defined at compile time. I kno
If it HAS TO BE a C++11 solution, then ignore this answer.
If not... I don't know if you already know this, but here is one option:
void * aligned_malloc( size_t size, size_t alignement )
{
void * p = malloc( size + --alignement );
void * p1 = (void*)( ( (size_t)p + alignement ) & ~alignement );
((char*)p1)[ -1 ] = (char)((char*)p1 - (char*)p);
return p1;
}
void aligned_free( void * pMem )
{
char * pDelete = (char*)pMem - ((char*)pMem)[ -1 ];
free( pDelete );
}
Perhaps malloc and free are not 100% portable, but it's easy to handle such cases with preprocessor directives.