From 8056fda650c3e953065cd00fe833446729a54708 Mon Sep 17 00:00:00 2001 From: Klemen Plestenjak Date: Thu, 8 Feb 2024 21:16:24 +0100 Subject: [PATCH] Fix memory leak with object pools --- game/systems/systems.c | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/game/systems/systems.c b/game/systems/systems.c index 526ae80..d0dea8e 100644 --- a/game/systems/systems.c +++ b/game/systems/systems.c @@ -48,12 +48,13 @@ ECS_DTOR(SpatialGridID, gridID, { }) ECS_MOVE(SpatialGridID, dst, src, { *dst = *src; + *src = 0; }) ECS_DTOR(Path, path, { Game *game = ecs_singleton_get_mut(ECS, Game); BzObjectPool *pool = game->pools.pathData; - PathData *cur = path[i].paths; + PathData *cur = path->paths; while (cur) { bzObjectPoolRelease(pool, cur); cur = cur->next; @@ -61,7 +62,22 @@ ECS_DTOR(Path, path, { }) ECS_MOVE(Path, dst, src, { *dst = *src; + src->paths = NULL; + src->curWaypoint = 0; }) +void pathRemoved(ecs_iter_t *it) { + Game *game = ecs_singleton_get_mut(ECS, Game); + BzObjectPool *pool = game->pools.pathData; + Path *path = ecs_field(it, Path, 1); + for (int i = 0; i < it->count; i++) { + PathData *cur = path[i].paths; + while (cur) { + bzObjectPoolRelease(pool, cur); + cur = cur->next; + } + path[i].paths = NULL; + } +} ECS_DTOR(Building, building, { Vec2i pos = building->pos; @@ -71,6 +87,7 @@ ECS_DTOR(Building, building, { }) ECS_MOVE(Building, dst, src, { *dst = *src; + *src = (Building) {.type = 0}; }) void delayDeleteUpdate(ecs_iter_t *it) { @@ -93,7 +110,8 @@ void setupSystems() { }); ecs_set_hooks(ECS, Path, { .dtor = ecs_dtor(Path), - .move_dtor = ecs_move(Path) + .move = ecs_move(Path), + .on_remove = pathRemoved }); ecs_set_hooks(ECS, Building, { .dtor = ecs_dtor(Building),