c / intermediate
Snippet
Memory Alignment with _Alignas
Certain hardware operations require data to be aligned to specific memory boundaries (e.g., 16-byte boundaries for SIMD instructions). The 'alignas' keyword (from C11) forces the compiler to insert padding to meet these alignment requirements.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>#include <stdalign.h>struct AlignedBuffer {char x;alignas(16) char buffer[16];};int main() {struct AlignedBuffer data;printf("Offset of buffer: %zu\n", (char*)&data.buffer - (char*)&data);return 0;}
Breakdown
1
#include <stdalign.h>
Header required for alignment macros like 'alignas'.
2
alignas(16) char buffer[16];
Ensures 'buffer' starts at an address that is a multiple of 16.
3
(char*)&data.buffer - (char*)&data
Calculates the offset; notice the compiler adds padding after 'x' to align the buffer.