Fixes memory issue in MemoryPool.
This commit is contained in:
parent
cf09f9348c
commit
9fcf296442
|
@ -22,7 +22,7 @@ namespace MalachScript::Parser {
|
|||
size_t _scriptLength;
|
||||
Diagnostics::Logger* _diagnostics;
|
||||
|
||||
Utils::MemoryPool<2048, 1024> _allocator;
|
||||
Utils::MemoryPool<4096> _allocator;
|
||||
|
||||
inline char8_t Consume() {
|
||||
if (++_position >= _scriptLength) {
|
||||
|
|
|
@ -6,24 +6,23 @@
|
|||
#include <stdexcept>
|
||||
|
||||
namespace MalachScript::Utils {
|
||||
template <size_t initialSize, size_t steps> class MemoryPool {
|
||||
template <size_t steps> class MemoryPool {
|
||||
public:
|
||||
MemoryPool() {
|
||||
auto* ptr = malloc(initialSize);
|
||||
if (ptr == nullptr) {
|
||||
throw std::logic_error("Out of memory.");
|
||||
}
|
||||
_head = static_cast<uint8_t*>(ptr);
|
||||
_tail = _head;
|
||||
_end = _head + initialSize;
|
||||
}
|
||||
MemoryPool() { AllocateBlock(); }
|
||||
MemoryPool(MemoryPool const&) = delete;
|
||||
MemoryPool& operator=(MemoryPool const&) = delete;
|
||||
|
||||
~MemoryPool() { free(_head); }
|
||||
~MemoryPool() {
|
||||
for (auto c : _chunks) {
|
||||
free(c);
|
||||
}
|
||||
}
|
||||
|
||||
template <class T, class... parameters> T* Create(parameters... args) {
|
||||
auto* p = _tail + sizeof(T);
|
||||
if (p >= _end) {
|
||||
IncreaseStep();
|
||||
AllocateBlock();
|
||||
p = _tail + sizeof(T);
|
||||
}
|
||||
auto* element = new (_tail) T(args...);
|
||||
_tail = p;
|
||||
|
@ -31,17 +30,20 @@ namespace MalachScript::Utils {
|
|||
}
|
||||
|
||||
private:
|
||||
std::vector<uint8_t*> _chunks;
|
||||
|
||||
uint8_t* _tail = nullptr;
|
||||
uint8_t* _end;
|
||||
uint8_t* _head = nullptr;
|
||||
|
||||
void IncreaseStep() {
|
||||
_end += steps;
|
||||
auto newPtr = realloc(_head, _end - _head);
|
||||
void AllocateBlock() {
|
||||
auto* newPtr = malloc(steps * sizeof(uint8_t*));
|
||||
if (newPtr == nullptr) {
|
||||
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);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue