Skip to content

Commit 33627a7

Browse files
authored
fix: Spawn Monsters memory leak (#538)
This PR fixes memory leak issues in spawn monsters.
1 parent 4a1b4dc commit 33627a7

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

src/creatures/monsters/spawns/spawn_monster.cpp

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -129,10 +129,18 @@ bool SpawnsMonster::loadFromXML(const std::string &filemonstername) {
129129
}
130130

131131
void SpawnsMonster::startup() {
132-
if (!isLoaded() || isStarted()) {
132+
if (!isLoaded()) {
133133
return;
134134
}
135135

136+
if (isStarted()) {
137+
for (const auto &spawnMonster : spawnMonsterList) {
138+
spawnMonster->stopEvent();
139+
spawnMonster->removeMonsters();
140+
}
141+
started = false;
142+
}
143+
136144
for (const auto &spawnMonster : spawnMonsterList) {
137145
spawnMonster->startup();
138146
}
@@ -143,6 +151,7 @@ void SpawnsMonster::startup() {
143151
void SpawnsMonster::clear() {
144152
for (const auto &spawnMonster : spawnMonsterList) {
145153
spawnMonster->stopEvent();
154+
spawnMonster->removeMonsters();
146155
}
147156
spawnMonsterList.clear();
148157

@@ -181,6 +190,7 @@ void SpawnMonster::startSpawnMonsterCheck() {
181190

182191
SpawnMonster::~SpawnMonster() {
183192
stopEvent();
193+
removeMonsters();
184194
}
185195

186196
// moveable
@@ -336,6 +346,9 @@ void SpawnMonster::cleanup() {
336346
for (auto it = spawnedMonsterMap.begin(); it != spawnedMonsterMap.end();) {
337347
const auto &monster = it->second;
338348
if (!monster || monster->isRemoved()) {
349+
if (monster) {
350+
monster->setSpawnMonster(nullptr);
351+
}
339352
auto spawnIt = spawnMonsterMap.find(it->first);
340353
if (spawnIt != spawnMonsterMap.end()) {
341354
spawnIt->second.lastSpawn = OTSYS_TIME();
@@ -425,10 +438,20 @@ void SpawnMonster::removeMonster(const std::shared_ptr<Monster> &monster) {
425438
break;
426439
}
427440
}
428-
spawnedMonsterMap.erase(spawnMonsterId);
441+
if (spawnMonsterId != 0) {
442+
if (monster) {
443+
monster->setSpawnMonster(nullptr);
444+
}
445+
spawnedMonsterMap.erase(spawnMonsterId);
446+
}
429447
}
430448

431449
void SpawnMonster::removeMonsters() {
450+
for (auto &[id, monster] : spawnedMonsterMap) {
451+
if (monster) {
452+
monster->setSpawnMonster(nullptr);
453+
}
454+
}
432455
spawnMonsterMap.clear();
433456
spawnedMonsterMap.clear();
434457
}

0 commit comments

Comments
 (0)