From fd6829257441036faf41e38a1ed8fa89ba917e3e Mon Sep 17 00:00:00 2001
From: Matthieu Schaller <schaller@strw.leidenuniv.nl>
Date: Wed, 20 Jun 2018 10:11:42 +0200
Subject: [PATCH] When computing the top-level cell index of particles, check
 that the positions are valid before accessing the array.

---
 src/space.c | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)

diff --git a/src/space.c b/src/space.c
index dfc6fb55cf..db7a25e012 100644
--- a/src/space.c
+++ b/src/space.c
@@ -1062,8 +1062,6 @@ void space_parts_get_cell_index_mapper(void *map_data, int nr_parts,
     /* Get its cell index */
     const int index =
         cell_getid(cdim, pos_x * ih_x, pos_y * ih_y, pos_z * ih_z);
-    ind[k] = index;
-    cell_counts[index]++;
 
 #ifdef SWIFT_DEBUG_CHECKS
     if (index < 0 || index >= cdim[0] * cdim[1] * cdim[2])
@@ -1076,6 +1074,9 @@ void space_parts_get_cell_index_mapper(void *map_data, int nr_parts,
             pos_z);
 #endif
 
+    ind[k] = index;
+    cell_counts[index]++;
+
     /* Compute minimal mass */
     min_mass = min(min_mass, hydro_get_mass(p));
 
@@ -1149,8 +1150,6 @@ void space_gparts_get_cell_index_mapper(void *map_data, int nr_gparts,
     /* Get its cell index */
     const int index =
         cell_getid(cdim, pos_x * ih_x, pos_y * ih_y, pos_z * ih_z);
-    ind[k] = index;
-    cell_counts[index]++;
 
 #ifdef SWIFT_DEBUG_CHECKS
     if (index < 0 || index >= cdim[0] * cdim[1] * cdim[2])
@@ -1163,6 +1162,9 @@ void space_gparts_get_cell_index_mapper(void *map_data, int nr_gparts,
             pos_z);
 #endif
 
+    ind[k] = index;
+    cell_counts[index]++;
+
     /* Compute minimal mass */
     if (gp->type == swift_type_dark_matter) {
       min_mass = min(min_mass, gp->mass);
@@ -1238,8 +1240,6 @@ void space_sparts_get_cell_index_mapper(void *map_data, int nr_sparts,
     /* Get its cell index */
     const int index =
         cell_getid(cdim, pos_x * ih_x, pos_y * ih_y, pos_z * ih_z);
-    ind[k] = index;
-    cell_counts[index]++;
 
 #ifdef SWIFT_DEBUG_CHECKS
     if (index < 0 || index >= cdim[0] * cdim[1] * cdim[2])
@@ -1252,6 +1252,9 @@ void space_sparts_get_cell_index_mapper(void *map_data, int nr_sparts,
             pos_z);
 #endif
 
+    ind[k] = index;
+    cell_counts[index]++;
+
     /* Compute minimal mass */
     min_mass = min(min_mass, sp->mass);
 
-- 
GitLab