Skip to content

Instantly share code, notes, and snippets.

@benloong
Created December 19, 2016 09:17
Show Gist options
  • Save benloong/9f430c14832a6f4dbec3df79d5e52bf4 to your computer and use it in GitHub Desktop.
Save benloong/9f430c14832a6f4dbec3df79d5e52bf4 to your computer and use it in GitHub Desktop.
aligned allocator
#pragma once
#include<memory>
template<int alignment>
struct aligned_allocator
{
static_assert((alignment&(alignment - 1)) == 0, "alignment must be power of 2.");
void* allocate(size_t size) {
size += alignment;
uint8_t* mem = (uint8_t*)std::malloc(size);
uint8_t* aligned = (uint8_t*) ((size_t) (mem + alignment) & (~(size_t)(alignment - 1)));
auto offset = aligned - mem;
aligned[-1] = (uint8_t)offset;
return aligned;
}
void free(void* addr) {
uint8_t* aligned = (uint8_t*)addr;
auto offset = aligned[-1];
std::free(aligned - offset);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment