In libc's malloc(x), the function is said to return a pointer to a memory region of at least x bytes and the pointer is aligned to 8 bytes. What does this alignment mean? THank you.
An object that is "8 bytes aligned" is stored at a memory address that is a multiple of 8. Many CPUs will only load some data types from aligned locations; on other CPUs such access is just faster. There's also several other possible reasons for using memory alignment - without seeing the code it's hard to say why.
new and malloc, by default, align address to 8 bytes (x86) or 16 bytes (x64), which is the optimal for most complex data.
A memory address a is said to be n-byte aligned when a is a multiple of n (where n is a power of 2). In this context, a byte is the smallest unit of memory access, i.e. each memory address specifies a different byte.
The GNU documentation states that malloc is aligned to 16 byte multiples on 64 bit systems.
It means that the pointed address mod 8 is 0:
pointer % 8 == 0
This can be important for low level operations where it may impact correctness or efficiency. See also this answer.
It means that the memory starts on an address that is a multiple of 8.
As for why you would even care: For memory that's not aligned, the CPU sometimes requires two accesses to read it all. In some cases, it won't even try and will just throw an error. The mention of "aligned to 8 bytes" is so that the caller knows whether it'll have to do any fudging of the pointer or not.
(Usually, you won't care -- the compiler takes care of most of the alignment issues for you. But the info's there in case you need it for some reason.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With