Most operating systems theses days return aligned pointers to dynamically allocated blocks of memory. However, this isn't always the case. So recently, I went about writing a simple (and I mean simple) memory manager to understand the effects of using misaligned pointers. Of course, the effects of placing data at a misaligned address is reduced performance.
So I began reading about pointer alignment. From what I've read, the address a pointer points to needs to be even and divisible by some alignment boundary. I know that CPUs read in a fixed-size byte-blocks (word), so it would make sense to align the pointer on a word-sized boundary.
The problem is, however, I don't actually know how to align a pointer. I've seen examples of pointer alignment which involve bit-masking, but the explanations they gave weren't exactly helpful. There were also examples of pointer alignment which involved the modulus operator; the pointer was converted from a pointer into an integral type but there was some debate about which integral type to use.
So how does one align a pointer to an alignment boundary? and which technique is portable?
std::align can align a pointer to the specified alignment, but of course you can't obtain an unaligned pointer from a standard dynamic allocation function to start with. (you may wish for something stricter though)
ps: the important thing to understand is that alignment is a property of type, and the proper way to over align objects is alignas (or compiler-specific type attributes where not yet supported)