Search code examples
c++cpointersalignment

About Pointer alignment, is there a way to make a pointer aligned to some given memory boundary?


What I want to do is NOT initilize a pointer that aligned to a given boundary, instead, it is like some function that can transform/copy the pointer (and the contents it is pointed to)'s phyiscal address to a aligned memory address back and forth, like alignedPtr() in the following code:

void func(double * x, int len)
{

//Change x's physical address to an aligned boundary and shift its data accordingly.
alignedPtr(x, len);


//do something...
};

Solution

  • Assuming that the size of the allocated buffer is sufficiently large i.e. len + alignment required, the implementation would require 2 steps.

    1. newPtr = ((orgPtr + (ALIGNMENT - 1)) & ALIGN_MASK); - This will generate the new pointer

    2. Since the intended design is to have an inplace computation, copy from newPtr + len backwards to avoid overwrite of data.