Allocate Aligned Memory with posix_memalign and aligned_alloc
Get memory aligned to 32, 64 or 4096 bytes with posix_memalign or C11 aligned_alloc, learn their rules and error codes, and pick the right one for SIMD or DMA.

malloc() returns memory aligned for any ordinary type, which on 64-bit Linux means a multiple of 16 bytes. That is enough for an int, a double and a struct of them, and not enough for a 32-byte AVX vector load, a 64-byte cache line you do not want to share with a neighbor, or a 4,096-byte page that a device or mprotect() needs. For those you ask for the alignment explicitly, and C and POSIX give you two functions to do it: posix_memalign() and aligned_alloc(). They are similar enough to confuse and different enough to bite, and this post sets out the rules, the errors and a choice.
The behavior follows ISO C11 and POSIX.1-2024, checked against glibc 2.40 on Linux 6.12 with GCC 14. Where musl or another C library differs, the text says so.
What alignment means
An address is aligned to N bytes when it is a multiple of N. Hardware cares because some instructions require it (an aligned SSE load, movaps, faults on an address that is not a multiple of 16), and some are faster with it. A 64-byte alignment keeps an object from straddling two cache lines, and it also stops two objects used by two threads from sharing a line, which causes false sharing. A page-aligned block, 4,096 bytes on x86-64, is a requirement when you hand the memory to mprotect(), madvise() or a device.
The standard answer for the alignment a type needs is alignof(type) from <stdalign.h>. For a type declared with alignas(64), you also need the heap block to honor it, and malloc() does not.
posix_memalign
int posix_memalign(void **memptr, size_t alignment, size_t size);It stores the new pointer in *memptr and returns zero on success. The rules from POSIX:
alignmentmust be a power of two and a multiple ofsizeof(void *), which is 8 on a 64-bit system.sizecan be any value, and need not be a multiple of the alignment.On failure it returns an error number,
EINVALfor a bad alignment orENOMEMfor no memory, and it does not seterrno, and*memptris left unspecified.The block is released with ordinary
free().
The return-value convention is the part people get wrong. You test the return value, not errno, and you convert it to text with strerror().
#define _POSIX_C_SOURCE 200809L
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
void *p = NULL;
int rc = posix_memalign(&p, 64, 1000);
if (rc != 0) {
fprintf(stderr, "posix_memalign: %s\n", strerror(rc));
return EXIT_FAILURE;
}
printf("address mod 64 = %zu\n", (size_t)((uintptr_t)p % 64));
free(p);
rc = posix_memalign(&p, 24, 100); /* 24 is not a power of two */
printf("alignment 24: %s\n", rc == 0 ? "ok" : strerror(rc));
rc = posix_memalign(&p, 4, 100); /* less than sizeof(void *) */
printf("alignment 4: %s\n", rc == 0 ? "ok" : strerror(rc));
return EXIT_SUCCESS;
}address mod 64 = 0
alignment 24: Invalid argument
alignment 4: Invalid argumentThe first call returns a pointer whose address is a multiple of 64 (the modulo prints zero) for a 1,000-byte request, and the size does not have to be a multiple of 64. The next two fail with EINVAL: 24 is not a power of two, and 4 is a power of two but smaller than sizeof(void *). On the failing calls p is not valid, so the demo does not use it.
aligned_alloc
void *aligned_alloc(size_t alignment, size_t size);Added in C11 and available in POSIX.1-2024, it returns the pointer directly, or NULL on failure with errno set. That makes it a closer match to malloc(). It has a rule that posix_memalign() does not: the C11 text says size must be an integral multiple of alignment, and an implementation may fail the call when it is not. glibc does not enforce the rule and returns a block anyway, and the C17 defect report 460 and later drafts relax it. Portable code ignores the relaxation and rounds the size up, which costs nothing:
#include <stdalign.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
static void *alloc_aligned(size_t alignment, size_t size)
{
size_t rounded = (size + alignment - 1) / alignment * alignment;
return aligned_alloc(alignment, rounded);
}
int main(void)
{
float *v = alloc_aligned(32, 100 * sizeof *v); /* 400 rounds up to 416 */
if (v == NULL) {
perror("aligned_alloc");
return EXIT_FAILURE;
}
printf("alignof(max_align_t) = %zu\n", alignof(max_align_t));
printf("v mod 32 = %zu\n", (size_t)((uintptr_t)v % 32));
free(v);
return EXIT_SUCCESS;
}alignof(max_align_t) = 16
v mod 32 = 0alignof(max_align_t) is 16 on 64-bit Linux, which is why plain malloc() would not guarantee the 32 bytes asked for here. The helper rounds 400 bytes up to 416, the next multiple of 32, so the call is valid under every reading of the standard.
Which one to use
posix_memalign() | aligned_alloc() | |
|---|---|---|
| Standard | POSIX | ISO C11, also in POSIX.1-2024 |
| Returns | 0 or an error number | pointer or NULL with errno |
| Size must be a multiple of alignment | No | Yes by the C11 text, not enforced by glibc |
Alignment less than sizeof(void *) | EINVAL | Permitted by C, and implementation defined |
| Available on Windows | No | No, MSVC offers _aligned_malloc() instead |
Pick aligned_alloc() when you want the malloc()-shaped interface and portable ISO C, and round the size. Pick posix_memalign() when the code is POSIX only and you do not want to think about size multiples. Both are released with free(), which is a real convenience over the old memalign() and valloc() functions, which are obsolete (memalign() is a glibc extension and valloc() was removed from POSIX).
On Windows neither exists in MSVC's C library, and the memory must be released with _aligned_free(), not free(). A portable library wraps allocation and release in a pair of functions, so the choice stays in one file.
Alignment of stack and static objects
For objects that are not on the heap, ask the compiler. In C11 and later, alignas(64) in <stdalign.h> (a keyword in C23) aligns a variable or a struct member:
#include <stdalign.h>
#include <stdint.h>
#include <stdio.h>
struct counter {
alignas(64) long hits; /* starts a new cache line */
long misses;
};
static alignas(32) float table[8];
int main(void)
{
struct counter c = {0};
printf("c.hits mod 64 = %zu\n", (size_t)((uintptr_t)&c.hits % 64));
printf("table mod 32 = %zu\n", (size_t)((uintptr_t)table % 32));
return 0;
}c.hits mod 64 = 0
table mod 32 = 0Alignment on the stack is honored by the compiler for ordinary alignas values. Very large ones, a page for example, are better placed in a static or heap block, since a deep stack frame with a 4,096-byte alignment wastes up to a page per call.
Mistakes to avoid
**Assuming malloc() gives 32 or 64.** It gives 16 on 64-bit glibc. Code that casts a malloc() pointer to an AVX type and uses an aligned load works on some blocks and faults on others, depending on the addresses the allocator happened to return.
Using the returned pointer after adjusting it. Some older code over-allocates and rounds a pointer up by hand. That pointer cannot be passed to free(), only the original one can. With aligned_alloc() the pointer is the one to free.
Forgetting that large alignments waste memory. Aligning every small object to 4,096 bytes costs a page each. If you need many aligned small objects, allocate one aligned slab and carve it up, which is what an arena does.
**Using realloc() on an aligned block.** realloc() guarantees only the default alignment for the result, so growing a 64-byte-aligned block may return a block that is not. Allocate a new aligned block and copy.
Aligned allocation in a real use: a SIMD buffer
The usual reason to want alignment is a vector loop. Aligned loads are required by some instructions and cheaper on others, and a buffer you allocate yourself is the place to guarantee it. A summing loop over an aligned float array lets the compiler use aligned vector loads once you tell it what you know, with __builtin_assume_aligned() in GCC and Clang:
#include <stdio.h>
#include <stdlib.h>
static float sum(const float *data, size_t n)
{
const float *v = __builtin_assume_aligned(data, 32);
float total = 0.0f;
for (size_t i = 0; i < n; i++) {
total += v[i];
}
return total;
}
int main(void)
{
size_t n = 64;
float *buf = aligned_alloc(32, n * sizeof *buf); /* 256 bytes, a multiple of 32 */
if (buf == NULL) {
return EXIT_FAILURE;
}
for (size_t i = 0; i < n; i++) {
buf[i] = 0.5f;
}
printf("sum = %.1f\n", sum(buf, n));
free(buf);
return EXIT_SUCCESS;
}sum = 32.0The __builtin_assume_aligned() call is a promise, not a check: if the pointer is not actually 32-byte aligned the behavior is undefined, and the compiler may emit an aligned load that faults. That is why the allocation and the assumption must sit close together, in code you can read side by side. Wherever you cannot guarantee the alignment, leave the promise out and let the compiler use unaligned loads, which are as fast as aligned ones on current x86-64 and arm64 cores when the data does not cross a cache line.


