Search code examples
c++cmemoryalignment

Memory alignment and long copies


If we assume that i align a block of memory with memalign to 4bytes , would it still be safe to do :

unsigned int* source = In.Data;
unsigned int* dest = Out.Data;

int loops = In.Size / 4; //size is the same for both in/out 

while (loops)
{
    *dest++=*source++;
    loops--;
}

Instead copying 1byte at a time? If not how to tell if the memory is properly aligned in order to fallback to standard byte copies if needed?


Solution

  • Yes, it is safe as your blocks are properly aligned.

    It would also be safe if get your blocks from malloc as the block of memory returned by malloc is guaranteed to be properly aligned for any purpose.