C++:alignas
lastmod 2018-08-17created 2016-11-188 edits
alignas
The alignas type specifier is a portable, C++ standard way to specify custom alignment of variables and user-defined types.
alignof
Similarly, the alignof operator is a portable, standard way to obtain the alignment of a specified type or variable.
align_malloc
- posix_memalign(3) - Linux man page
- Stackoverflow - OSX lacks memalign
- Stackoverflow - Why use _mm_malloc? (as opposed to _aligned_malloc, alligned_alloc, or posix_memalign)
- MSDN - _aligned_malloc
- posix_memalign(3) - Linux manual page
- Stackoverflow - aligned malloc() in GCC?
- Getting the Most from OpenCL™ 1.2: How to Increase Performance by Minimizing Buffer Copies on Intel® Processor Graphics 1
int *pbuf = (int *)_aligned_malloc(sizeof(int) * 1024, 4096);
// ...
unsigned int verifyZeroCopyPtr(void *ptr, unsigned int sizeOfContentsOfPtr)
{
int status; //so we only have one exit point from function
if((uintptr_t)ptr % 4096 == 0) { // page alignment and cache alignment
if(sizeOfContentsOfPtr % 64 == 0) { // multiple of cache size
status = 1;
} else {
status = 0;
}
} else {
status = 0;
}
return status;
}
Example
struct alignas(16) Bar
{
int i; // 4 bytes
int n; // 4 bytes
alignas(4) char arr[3];
short s; // 2 bytes
};
// ...
cout << alignof(Bar) << endl; // output: 16
Troubleshooting
MacOS X memory alignment
I had a hard time finding a definitive statement on MacOS X memory alignment so I did my own tests. On 10.4/intel, both stack and heap memory is 16 byte aligned. So people porting software can stop looking for memalign() and posix_memalign(). It’s not needed.
See also
Favorite site
References
Pages that link here