Topics / Pointers & Memory / Q29
Allocate 64-byte-aligned memory using sizeof without malloc or calloc
You can use sizeof to calculate the required memory size and declare a buffer with 63 extra bytes for 64-byte alignment.
#include <stdio.h>
#include <stdint.h>
int main()
{
int arr[100];
uint8_t buffer[sizeof(arr) + 63];
uintptr_t addr = (uintptr_t)buffer;
addr = (addr + 63) & ~(uintptr_t)63;
int *ptr = (int *)addr;
printf("Original address: %p\n", (void *)buffer);
printf("Aligned address: %p\n", (void *)ptr);
printf("Is aligned: %d\n", !(addr & 63));
return 0;
}
This example demonstrates address alignment only. The buffer is automatic storage, and the cast does not make the declared byte array an int array; do not access it through int * as if it were one. For actual integer storage use the aligned int array below.
Simpler approach using C11
If you want to allocate memory for 100 integers without an additional array:
#include <stdint.h>
_Alignas(64) uint8_t buffer[100 * sizeof(int)];
Or directly:
_Alignas(64) int buffer[100];
Important: sizeof itself does not allocate memory. It calculates the size in bytes. The array declaration allocates the memory.
The key bitwise formula to remember for interviews is:
aligned_addr = (addr + 63) & ~(uintptr_t)63;
This rounds the address up to the nearest 64-byte boundary.