Pointer Alignment

closed account (zb0S216C)
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?


> but there was some debate about which integral type to use.

There is no debate. std::uintptr_t in <cstdint>
closed account (zb0S216C)
Isn't "uintptr_t" optional?

P.S: Thanks for replying :)

In theory it is optional.

If it is not there, the best we can do is std::uintmax_t
with a check sizeof(std::uintmax_t) >= sizeof(void*)
Last edited on
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)
Last edited on
closed account (zb0S216C)
That makes sense. So is "uintmax_t" guaranteed to be defined in "cstdint"?

Also, is there any articles or books you know of which cover pointer alignment? It's giving me a headache.

Thanks, JLBorges.

> So is "uintmax_t" guaranteed to be defined in "cstdint"?


> It's giving me a headache.

Cubbi +1

Just use std:align() for alignment.

And use std::uintptr_t for numeric computations (eg. for a custom hash function)
closed account (zb0S216C)
Thanks, Cubbi & JLBorges :) Appreciated.

Topic archived. No new replies allowed.