Skip to content

Commit 6d8736f

Browse files
committed
Better malloc / free for GameEngine
1 parent eb7817d commit 6d8736f

1 file changed

Lines changed: 32 additions & 10 deletions

File tree

src/port/Engine.cpp

Lines changed: 32 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@
2525
#include <filesystem>
2626
#include <fstream>
2727

28+
#include <cstdlib>
29+
#include <algorithm>
30+
2831
#ifdef USE_NETWORKING
2932
#include <SDL2/SDL_net.h>
3033
#endif
@@ -997,14 +1000,19 @@ void GameEngine::Create(int argc, char* argv[]) {
9971000
void GameEngine::Destroy() {
9981001
GhostshipGui::Destroy();
9991002
gsFast3dWindow = nullptr;
1000-
Instance->context = nullptr;
10011003
AudioExit();
10021004
#ifdef __SWITCH__
10031005
Ship::Switch::Exit();
10041006
#endif
1005-
for (auto& entry : Instance->memoryPool) {
1006-
delete[] entry.addr;
1007+
auto& pool = GameEngine::Instance->memoryPool;
1008+
1009+
for (auto& entry : pool) {
1010+
if (entry.addr != nullptr) {
1011+
std::free(entry.addr);
1012+
}
10071013
}
1014+
1015+
pool.clear();
10081016
}
10091017

10101018
void GameEngine::StartFrame() const {
@@ -1600,18 +1608,32 @@ extern "C" void* GameEngine_GetExactDataByName(const char* path) {
16001608
extern "C" void* GameEngine_Malloc(size_t size) {
16011609
auto& pool = GameEngine::Instance->memoryPool;
16021610

1603-
pool.push_back({ new uint8_t[size], size });
1604-
return (void*)pool.back().addr;
1611+
uint8_t* ptr = static_cast<uint8_t*>(std::malloc(size));
1612+
1613+
if (ptr) {
1614+
pool.push_back({ ptr, size });
1615+
}
1616+
1617+
return ptr;
16051618
}
16061619

16071620
extern "C" void GameEngine_Free(void* ptr) {
1621+
if (!ptr) {
1622+
return;
1623+
}
1624+
16081625
auto& pool = GameEngine::Instance->memoryPool;
16091626

1610-
for (auto it = pool.begin(); it != pool.end(); ++it) {
1611-
if (it->addr == ptr) {
1612-
delete[] it->addr;
1613-
pool.erase(it);
1614-
break;
1627+
for (size_t i = 0; i < pool.size(); ++i) {
1628+
if (pool[i].addr == ptr) {
1629+
std::free(pool[i].addr);
1630+
1631+
if (i != pool.size() - 1) {
1632+
std::swap(pool[i], pool.back());
1633+
}
1634+
1635+
pool.pop_back();
1636+
return;
16151637
}
16161638
}
16171639
}

0 commit comments

Comments
 (0)