Last active
October 1, 2019 15:52
-
-
Save ashwin/acde4e7bff4b1bc86e5216931fadea5b to your computer and use it in GitHub Desktop.
Aligned memory allocation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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
Neat code but you need to check malloc