How do you allocate memory that\'s aligned to a specific boundary in C (e.g., cache line boundary)? I\'m looking for malloc/free like implementation that ideally would be as po
Here is a solution, which encapsulates the call to malloc, allocates a bigger buffer for alignment purpose, and stores the original allocated address just before the aligned buffer for a later call to free.
// cache line
#define ALIGN 64
void *aligned_malloc(int size) {
void *mem = malloc(size+ALIGN+sizeof(void*));
void **ptr = (void**)((uintptr_t)(mem+ALIGN+sizeof(void*)) & ~(ALIGN-1));
ptr[-1] = mem;
return ptr;
}
void aligned_free(void *ptr) {
free(((void**)ptr)[-1]);
}