Skip to content
systemcoding.dev
Toolchains

Align Data With __attribute__((aligned)) and alignas

Raise the alignment of variables, structs and heap buffers with __attribute__((aligned(n))), alignas and aligned_alloc for cache lines, SIMD and DMA.

6 min read
Summarize in AI
Flat illustration of source code passing through a compiler and linker into a binary, with the GNU, C and CMake logos.

Every object in C has an alignment: a number such that its address must be a multiple of that number. The compiler picks a default from the type, and most of the time the default is right. Sometimes it is not. SIMD loads run faster, or only work, when the buffer starts on a 16, 32 or 64-byte boundary. Two counters updated by different threads should sit on different cache lines. A DMA descriptor may have to start on a boundary the hardware dictates. For those cases you raise the alignment yourself, and C gives you three tools: the GNU aligned attribute, the C11 _Alignas specifier with its alignas macro, and the allocation functions for heap memory. This post shows each, how to check the result, and where each one stops working. The examples use GCC 14 on x86-64 Linux with glibc 2.40.

The three spellings

The GNU attribute attaches to a variable, a struct member or a type:

c
char buf[256] __attribute__((aligned(64)));

The standard form arrived in C11 as _Alignas(n), with a convenience macro alignas in <stdalign.h>. In C23 alignas is a keyword and needs no header, and alignof replaces _Alignof.

c
#include <stdalign.h>

alignas(64) char buf2[256];

Both produce an object whose address is a multiple of 64. The differences are small. aligned works on types and can be written after the declarator; alignas goes before the declaration. aligned with no argument asks for the largest alignment the target ever uses, 16 bytes on x86-64, which is what the compiler uses for the widest scalar and SIMD types. alignas requires a power of two, and so does aligned. The standard form is accepted by Clang, MSVC and every conforming C11 compiler, so prefer it in portable code and keep the attribute for places where you need it on a typedef or you build as C99.

Checking what you got

Print the addresses and the type alignments to see the result. _Alignof is C11; the GNU spelling __alignof__ works earlier.

align1.cc
#include <stdalign.h>
#include <stdint.h>
#include <stdio.h>

static char plain[10];
static alignas(32) char wide[10];
static char attr[10] __attribute__((aligned(64)));

int main(void)
{
    printf("alignof(plain)=%zu alignof(wide)=%zu alignof(attr)=%zu\n",
           alignof(plain), alignof(wide), alignof(attr));
    printf("wide%%32=%lu attr%%64=%lu\n",
           (unsigned long)((uintptr_t)wide % 32),
           (unsigned long)((uintptr_t)attr % 64));
    return 0;
}
Text
alignof(plain)=1 alignof(wide)=32 alignof(attr)=64
wide%32=0 attr%64=0

plain is an array of char, so its alignment is 1. The other two were raised, and the remainders confirm the addresses. The linker places each object in its section at a matching offset, and it raises the section's own alignment to the largest request, which readelf -S shows in the final column for .bss or .data.

Aligning a struct and what it does to size

Putting the attribute on a struct type raises its alignment, and sizeof rounds up to a multiple of that alignment, because arrays of the struct must keep every element aligned. That is the standard way to give each element of an array its own cache line:

align2.cc
#include <stdalign.h>
#include <stdio.h>

struct counter {
    long value;
} __attribute__((aligned(64)));

struct counter per_thread[4];

int main(void)
{
    printf("sizeof(struct counter)=%zu alignof=%zu\n",
           sizeof(struct counter), alignof(struct counter));
    printf("sizeof(per_thread)=%zu\n", sizeof per_thread);
    return 0;
}
Text
sizeof(struct counter)=64 alignof=64
sizeof(per_thread)=256

An eight-byte member now occupies 64 bytes. Four threads updating per_thread[i].value touch four different cache lines, which avoids false sharing, the slowdown where cores fight for ownership of a line that holds unrelated variables. The 64-byte figure is the line size on current x86-64 and many Arm cores, but it is a property of the hardware, not of the language. Check the target's documentation, and on Linux you can read /sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size. C++17 has std::hardware_destructive_interference_size for the same purpose, though GCC warns that its value is not stable across compiler flags.

Heap memory: aligned_alloc and posix_memalign

An attribute cannot change what malloc returns. malloc guarantees alignment suitable for any fundamental type, which is 16 bytes on x86-64 glibc. For more, use aligned_alloc from C11 or posix_memalign from POSIX:

align3.cc
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    float *v = aligned_alloc(64, 1024);
    if (!v)
        return 1;
    printf("v%%64=%lu\n", (unsigned long)((uintptr_t)v % 64));
    free(v);

    void *w = NULL;
    if (posix_memalign(&w, 4096, 8192) != 0)
        return 1;
    printf("w%%4096=%lu\n", (unsigned long)((uintptr_t)w % 4096));
    free(w);
    return 0;
}
Text
v%64=0
w%4096=0

aligned_alloc requires the size to be a multiple of the alignment in C11, and glibc accepts other sizes as an extension while some libraries return null. The safe habit is to round the size up yourself. Both functions return memory you release with plain free. For a type you allocate often, define the alignment on the type with the attribute and use aligned_alloc(alignof(T), sizeof(T) * n), so the two stay in sync.

Telling the compiler about alignment it cannot see

Raising alignment of an object you declare is half of the story. A function that receives a pointer does not know that the caller aligned it. If you want the compiler to use aligned vector loads, say so with a builtin:

align4.cc
void scale(float *restrict out, const float *restrict in, int n)
{
    float *o = __builtin_assume_aligned(out, 32);
    const float *i = __builtin_assume_aligned(in, 32);
    for (int k = 0; k < n; k++)
        o[k] = i[k] * 2.0f;
}

__builtin_assume_aligned(p, 32) returns p and promises that it is a multiple of 32. If the promise is false, the program has undefined behavior, and an aligned vector instruction such as vmovaps raises a general protection fault. Pair the promise with a check at the call boundary, for example an assert(((uintptr_t)out & 31) == 0) in debug builds. Modern x86-64 CPUs load unaligned data with vmovups at nearly the same speed as aligned data when it does not cross a cache line, so the gain is smaller than it was in 2005; measure before assuming it matters.

Limits and traps

  • Maximum alignment. GCC supports alignment up to a target-defined limit for static data, which on ELF is large. Stack variables are more limited, and a request above the stack's guaranteed alignment makes the compiler realign the frame at function entry, costing a few instructions and a spare register. A very large alignment on a local is better replaced by a static or heap buffer.

  • The attribute cannot lower alignment. On a variable or a type, aligned can only increase the value, except when combined with packed, where it sets the alignment exactly. A request for a smaller alignment is ignored.

  • Over-aligned types in containers. malloc-based allocators in C++ before C++17 did not honor alignas above 16. C++17 added aligned new. In C, any allocator you wrote yourself must honor the alignment, or the objects will be misaligned despite the declaration.

  • Alignment is not padding control. aligned raises the address requirement; it does not stop padding between members. Use packed for that.

  • Section placement. An object in a custom section, as in the section attribute post of this series, inherits the largest alignment among its members, so one 4096-aligned object forces the whole section to a page boundary.

Which one to use

For new code, write alignas(n) on variables and members and alignof(T) in expressions. Add #include <stdalign.h> for C11 and C17. Use __attribute__((aligned(n))) when you are on a compiler that has no alignas, or when you need the alignment on a typedef or a struct type definition in a header that must also compile as C99. Use aligned_alloc or posix_memalign for heap buffers, and __builtin_assume_aligned where you want the optimizer to use that fact. Verify with alignof, a pointer remainder in a test, and readelf -S on the object.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.