The aligned_alloc function
What you'll learn: How to request memory that starts at a specific hardware-friendly boundary for high-performance computing.
The "Grid" of Memory
Imagine you are parking a fleet of wide trucks in a parking lot. Standard memory allocation (malloc) is like a parking attendant who puts cars wherever they fit. Most of the time, this is fine. However, some heavy-duty "trucks"—like specialized CPU instructions used for graphics or high-speed math—are picky. They require the vehicle to be parked exactly on a line divisible by 16, 32, or 64. If a truck overlaps two parking spots awkwardly, the CPU has to work twice as hard to move it.
This requirement is called memory alignment. While malloc provides memory aligned for any standard data type, aligned_alloc gives you the power to specify a custom boundary.
How aligned_alloc Works
Introduced in C11, aligned_alloc takes two arguments: the alignment (the boundary) and the size (the amount of memory).
There are two strict rules to follow:
- The alignment must be a valid power of two (like 8, 16, 32, or 64).
- The size you request must be an integral multiple of the alignment. If you want a 64-byte alignment, you must ask for 64, 128, or 192 bytes, and so on.
#include <stdlib.h>
#include <stdio.h>
int main() {
size_t alignment = 64; // Align to a 64-byte boundary (common for cache lines)
size_t size = 1024; // 1024 is a multiple of 64
// Requesting aligned memory
void *ptr = aligned_alloc(alignment, size);
if (ptr == NULL) {
return 1; // Allocation failed
}
// Check if the address is actually divisible by 64
if (((uintptr_t)ptr % alignment) == 0) {
printf("Memory is perfectly aligned!\n");
}
// Use it like normal memory, then free it
free(ptr);
return 0;
}
When to Use It
You won't need aligned_alloc for every day int or char arrays. You use it when you are working with SIMD (Single Instruction, Multiple Data) instructions, where the processor processes huge chunks of data at once. By aligning the memory, you ensure the data flows into the CPU in one clean "gulp" rather than two messy ones, significantly boosting performance.
Key takeaway
Use aligned_alloc to place memory at specific address boundaries, ensuring the size is a multiple of the alignment.