Skip to content

Instantly share code, notes, and snippets.

@ashwin
Last active October 1, 2019 15:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ashwin/acde4e7bff4b1bc86e5216931fadea5b to your computer and use it in GitHub Desktop.
Save ashwin/acde4e7bff4b1bc86e5216931fadea5b 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]);
}
@daveyc
Copy link

daveyc commented Jul 18, 2018

Neat code but you need to check malloc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment