From 0bea33bc4ddbe79ecba60ba8e1ce9816057b05b6 Mon Sep 17 00:00:00 2001
From: Andreas Gattringer <andreas.gattringer@univie.ac.at>
Date: Sun, 16 Apr 2023 19:36:58 +0200
Subject: [PATCH] fixed cleanup-on-exit crash

---
 src/cats/grids/cats_grid.c         | 9 ++++++---
 src/cats/plants/plant_structures.c | 1 +
 2 files changed, 7 insertions(+), 3 deletions(-)

diff --git a/src/cats/grids/cats_grid.c b/src/cats/grids/cats_grid.c
index 41ce132..61ba302 100644
--- a/src/cats/grids/cats_grid.c
+++ b/src/cats/grids/cats_grid.c
@@ -251,30 +251,33 @@ void cleanup_grid_seeds_and_juveniles(struct cats_grid *grid)
 
         free_grid(&grid->seeds_produced, grid->dimension.rows);
         free_grid(&grid->dispersed_seeds, grid->dimension.rows);
+
         if (grid->seed_bank) {
                 for (cats_dt_coord row = 0; row < grid->dimension.rows; row++) {
                         for (cats_dt_coord col = 0; col < grid->dimension.cols; col++) {
                                 destroy_seed_structure(grid, row, col);
                         }
 
-                        free(grid->juveniles[row]);
+                        free(grid->seed_bank[row]);
                 }
         }
 
-        if (grid->seed_bank) {
+        if (grid->juveniles) {
                 for (cats_dt_coord row = 0; row < grid->dimension.rows; row++) {
                         for (cats_dt_coord col = 0; col < grid->dimension.cols; col++) {
                                 destroy_juveniles(grid, row, col);
                         }
 
                         free(grid->juveniles[row]);
+                        grid->juveniles[row] = NULL;
                 }
         }
 
 
         free(grid->seed_bank);
         free(grid->juveniles);
-        free(grid->seeds_produced);
+        grid->juveniles = NULL;
+        grid->seed_bank = NULL;
 }
 
 
diff --git a/src/cats/plants/plant_structures.c b/src/cats/plants/plant_structures.c
index be4613a..d75d8f4 100644
--- a/src/cats/plants/plant_structures.c
+++ b/src/cats/plants/plant_structures.c
@@ -114,6 +114,7 @@ void destroy_juveniles(const struct cats_grid *grid, const cats_dt_coord row, co
         assert(stages >= 0);
 
         if (grid->juveniles[row] && grid->juveniles[row][col]) {
+                memset(grid->juveniles[row][col], 0, stages * sizeof(cats_dt_population));
                 free(grid->juveniles[row][col]);
                 grid->juveniles[row][col] = NULL;
         }
-- 
GitLab