| Framework (3237) | |
|
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? Cheers! Wazzak | |
|
|
|
| JLBorges (1754) | |
|
> but there was some debate about which integral type to use. There is no debate. std::uintptr_t in <cstdint>
| |
|
|
|
| Framework (3237) | |
|
Isn't "uintptr_t" optional? P.S: Thanks for replying :) Wazzak | |
|
|
|
| JLBorges (1754) | |
|
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
|
|
| Cubbi (1925) | |
|
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) http://en.cppreference.com/w/cpp/memory/align 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
|
|
| Framework (3237) | |
|
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. Wazzak | |
|
|
|
| JLBorges (1754) | |
|
> So is "uintmax_t" guaranteed to be defined in "cstdint"? Yes. > 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)
| |
|
|
|
| Framework (3237) | |
|
Thanks, Cubbi & JLBorges :) Appreciated. Wazzak | |
|
|
|