Fixes memory issue in MemoryPool.

This commit is contained in:
Deukhoofd 2021-01-04 13:33:29 +01:00
parent cf09f9348c
commit 9fcf296442
Signed by: Deukhoofd
GPG Key ID: F63E044490819F6F
2 changed files with 19 additions and 17 deletions

View File

@ -22,7 +22,7 @@ namespace MalachScript::Parser {
size_t _scriptLength; size_t _scriptLength;
Diagnostics::Logger* _diagnostics; Diagnostics::Logger* _diagnostics;
Utils::MemoryPool<2048, 1024> _allocator; Utils::MemoryPool<4096> _allocator;
inline char8_t Consume() { inline char8_t Consume() {
if (++_position >= _scriptLength) { if (++_position >= _scriptLength) {

View File

@ -6,24 +6,23 @@
#include <stdexcept> #include <stdexcept>
namespace MalachScript::Utils { namespace MalachScript::Utils {
template <size_t initialSize, size_t steps> class MemoryPool { template <size_t steps> class MemoryPool {
public: public:
MemoryPool() { MemoryPool() { AllocateBlock(); }
auto* ptr = malloc(initialSize); MemoryPool(MemoryPool const&) = delete;
if (ptr == nullptr) { MemoryPool& operator=(MemoryPool const&) = delete;
throw std::logic_error("Out of memory.");
}
_head = static_cast<uint8_t*>(ptr);
_tail = _head;
_end = _head + initialSize;
}
~MemoryPool() { free(_head); } ~MemoryPool() {
for (auto c : _chunks) {
free(c);
}
}
template <class T, class... parameters> T* Create(parameters... args) { template <class T, class... parameters> T* Create(parameters... args) {
auto* p = _tail + sizeof(T); auto* p = _tail + sizeof(T);
if (p >= _end) { if (p >= _end) {
IncreaseStep(); AllocateBlock();
p = _tail + sizeof(T);
} }
auto* element = new (_tail) T(args...); auto* element = new (_tail) T(args...);
_tail = p; _tail = p;
@ -31,17 +30,20 @@ namespace MalachScript::Utils {
} }
private: private:
std::vector<uint8_t*> _chunks;
uint8_t* _tail = nullptr; uint8_t* _tail = nullptr;
uint8_t* _end; uint8_t* _end;
uint8_t* _head = nullptr; uint8_t* _head = nullptr;
void IncreaseStep() { void AllocateBlock() {
_end += steps; auto* newPtr = malloc(steps * sizeof(uint8_t*));
auto newPtr = realloc(_head, _end - _head);
if (newPtr == nullptr) { if (newPtr == nullptr) {
throw std::logic_error("Out of memory."); throw std::logic_error("Out of memory.");
} }
_head = static_cast<uint8_t*>(newPtr); _tail = _head = static_cast<uint8_t*>(newPtr);
_end = _head + (steps * sizeof(uint8_t*));
_chunks.push_back(_head);
} }
}; };
} }