Make absolutely sure allocated frame memory is always 16-byte aligned

This commit is contained in:
Magnus Norddahl 2019-11-23 02:26:52 +01:00
parent bc37d8d601
commit b7745aaa8b
2 changed files with 42 additions and 2 deletions

View file

@ -37,6 +37,7 @@
#include "po_man.h" #include "po_man.h"
#include "r_data/colormaps.h" #include "r_data/colormaps.h"
#include "r_memory.h" #include "r_memory.h"
#include <stdlib.h>
void *RenderMemory::AllocBytes(int size) void *RenderMemory::AllocBytes(int size)
{ {
@ -73,3 +74,42 @@ void RenderMemory::Clear()
FreeBlocks.push_back(std::move(block)); FreeBlocks.push_back(std::move(block));
} }
} }
static void* aligned_alloc(size_t alignment, size_t size)
{
void* ptr;
#if defined _MSC_VER
ptr = _aligned_malloc(size, alignment);
if (!ptr)
throw std::bad_alloc();
#else
// posix_memalign required alignment to be a min of sizeof(void *)
if (alignment < sizeof(void*))
alignment = sizeof(void*);
if (posix_memalign((void**)&ptr, alignment, size))
throw std::bad_alloc();
#endif
return ptr;
}
static void aligned_free(void* ptr)
{
if (ptr)
{
#if defined _MSC_VER
_aligned_free(ptr);
#else
free(ptr);
#endif
}
}
RenderMemory::MemoryBlock::MemoryBlock() : Data(static_cast<uint8_t*>(aligned_alloc(16, BlockSize))), Position(0)
{
}
RenderMemory::MemoryBlock::~MemoryBlock()
{
aligned_free(Data);
}

View file

@ -29,8 +29,8 @@ private:
struct MemoryBlock struct MemoryBlock
{ {
MemoryBlock() : Data(new uint8_t[BlockSize]), Position(0) { } MemoryBlock();
~MemoryBlock() { delete[] Data; } ~MemoryBlock();
MemoryBlock(const MemoryBlock &) = delete; MemoryBlock(const MemoryBlock &) = delete;
MemoryBlock &operator=(const MemoryBlock &) = delete; MemoryBlock &operator=(const MemoryBlock &) = delete;