Skip to content

Instantly share code, notes, and snippets.

@equalent
Forked from ashwin/aligned_malloc.cpp
Created October 1, 2019 15:52
Show Gist options
  • Save equalent/6c9398a8cad4de17ab94cf772a02026a to your computer and use it in GitHub Desktop.
Save equalent/6c9398a8cad4de17ab94cf772a02026a to your computer and use it in GitHub Desktop.
Aligned memory allocation
// Assume we need 32-byte alignment for AVX instructions
#define ALIGN 32
void *aligned_malloc(int size)
{
// We require whatever user asked for PLUS space for a pointer
// PLUS space to align pointer as per alignment requirement
void *mem = malloc(size + sizeof(void*) + (ALIGN - 1));
// Location that we will return to user
// This has space *behind* it for a pointer and is aligned
// as per requirement
void *ptr = (void**)((uintptr_t) (mem + (ALIGN - 1) + sizeof(void*)) & ~(ALIGN - 1));
// Sneakily store address returned by malloc *behind* user pointer
// void** cast is cause void* pointer cannot be decremented, cause
// compiler has no idea "how many" bytes to decrement by
((void **) ptr)[-1] = mem;
// Return user pointer
return ptr;
}
void aligned_free(void *ptr)
{
// Sneak *behind* user pointer to find address returned by malloc
// Use that address to free
free(((void**) ptr)[-1]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment