Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the alignment parameter for Boost aligned_allocator mean?

There is a Boost tutorial giving approximately the following code, slightly modified for my question:

#include <boost/align/aligned_allocator.hpp>
#include <vector>
int main()
{
  std::vector<int, boost::alignment::
    aligned_allocator<int, 16> > v(100);
}

In this example, an alignment parameter of 16 is given. Does this indicate 16 bytes of alignment, or 16*sizeof(int) bytes of alignment?

like image 743
bean Avatar asked Jul 01 '26 02:07

bean


1 Answers

It would represent 16 bytes of alignment.

On some processors, access to a non-aligned memory address can result in an exception. On others, a non-aligned memory access might work, but may be suboptimal, possibly requiring extra reads of memory at aligned addresses. The actual alignment needed or desired varies depending on context.

For example, on a 32-bit x86 processor a 32-bit (4 byte) non-aligned access can result in two aligned memory accesses. If a 4 byte read was done at address 1, the processor may need to read bytes 0..3, followed by a read of bytes 4..7, and then combine bytes 1..4 into the result, discarding the extra data read.

For SIMD instructions the alignment is greater. A 64-bit MMX instruction should access memory that is 64-bit (8 byte) aligned. A 128-bit XMM instruction should access memory that is 128-bit (16 byte) aligned.

On a SPARC processor an unaligned memory access would result in a processor exception. I believe ARM also generates exceptions for unaligned access. On x86 you can also get exceptions in some cases. In particular, if the stack is not properly aligned, it can cause a program crash. A detail that is usually handled by the compiler.

like image 187
Daniel Stevens Avatar answered Jul 02 '26 16:07

Daniel Stevens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!