diff --git a/src/Battling/EventHooks/EventHook.hpp b/src/Battling/EventHooks/EventHook.hpp index e70fb77..7e41b8c 100644 --- a/src/Battling/EventHooks/EventHook.hpp +++ b/src/Battling/EventHooks/EventHook.hpp @@ -15,7 +15,7 @@ namespace CreatureLib::Battling { private: std::vector _listeners; - size_t _position; + size_t _offset; size_t _capacity; uint8_t* _memory = nullptr; @@ -23,34 +23,37 @@ namespace CreatureLib::Battling { static const size_t defaultSize = 1024; public: - EventHook() : _position(0), _capacity(defaultSize), _memory(static_cast(malloc(defaultSize))) { - if (_memory == nullptr) { + EventHook() : _offset(0), _capacity(defaultSize) { + auto ptr = calloc(defaultSize, 1); + if (ptr == nullptr) { THROW_CREATURE("Out of memory."); } + _memory = static_cast(ptr); } EventHook(const EventHook&) = delete; EventHook& operator=(const EventHook&) = delete; ~EventHook() { free(_memory); } - size_t GetPosition() const noexcept { return _position; } + size_t GetPosition() const noexcept { return _offset; } size_t GetCapacity() const noexcept { return _capacity; } template void Trigger(parameters... args) { if (_listeners.size() == 0) return; - if (_position + sizeof(T) >= _capacity) { + if (_offset + sizeof(T) >= _capacity) { _capacity += defaultSize; - _memory = static_cast(realloc(_memory, _capacity)); - if (_memory == nullptr) { + auto newPtr = realloc(_memory, _capacity); + if (newPtr == nullptr) { THROW_CREATURE("Out of memory."); } + _memory = static_cast(newPtr); } - uint8_t* ptr = _memory + _position; + uint8_t* ptr = _memory + _offset; T* event = new (ptr) T(args...); - _position += sizeof(T); + _offset += sizeof(T); for (auto listener : _listeners) { - listener(event); + try_creature(listener(event), "Exception in event listener"); } }