Here is the code I normally use to get aligned memory with Visual Studio and GCC
inline void* aligned_malloc(size_t size, size_t align) {
void *result;
If you compiler supports it, C++11 adds a std::align function to do runtime pointer alignment. You could implement your own malloc/free like this (untested):
template
void *aligned_malloc(std::size_t size)
{
std::size_t space = size + (Align - 1);
void *ptr = malloc(space + sizeof(void*));
void *original_ptr = ptr;
char *ptr_bytes = static_cast(ptr);
ptr_bytes += sizeof(void*);
ptr = static_cast(ptr_bytes);
ptr = std::align(Align, size, ptr, space);
ptr_bytes = static_cast(ptr);
ptr_bytes -= sizeof(void*);
std::memcpy(ptr_bytes, original_ptr, sizeof(void*));
return ptr;
}
void aligned_free(void* ptr)
{
void *ptr_bytes = static_cast(ptr);
ptr_bytes -= sizeof(void*);
void *original_ptr;
std::memcpy(&original_ptr, ptr_bytes, sizeof(void*));
std::free(original_ptr);
}
Then you don't have to keep the original pointer value around to free it. Whether this is 100% portable I'm not sure, but I hope someone will correct me if not!