From a507a5180b2c9f2930f84d3612ea19d7d0fd9419 Mon Sep 17 00:00:00 2001
From: "Peter W. Draper" <p.w.draper@durham.ac.uk>
Date: Fri, 29 Apr 2016 15:54:06 +0100
Subject: [PATCH] When moving foreign particles to the end of the list, make
 sure we don't swap with one that is a foreign particle.

---
 src/space.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)

diff --git a/src/space.c b/src/space.c
index 93af4222b7..571cf09e3c 100644
--- a/src/space.c
+++ b/src/space.c
@@ -433,7 +433,7 @@ void space_rebuild(struct space *s, double cell_max, int verbose) {
 #ifdef WITH_MPI
   /* Move non-local parts to the end of the list. */
   const int local_nodeID = s->e->nodeID;
-  for (size_t k = 0; k < nr_parts; k++)
+  for (size_t k = 0; k < nr_parts;) {
     if (cells[ind[k]].nodeID != local_nodeID) {
       cells[ind[k]].count -= 1;
       nr_parts -= 1;
@@ -453,9 +453,14 @@ void space_rebuild(struct space *s, double cell_max, int verbose) {
       ind[k] = ind[nr_parts];
       ind[nr_parts] = t;
     }
+    else {
+      /* Increment when not exchanging otherwise we need to retest "k".*/
+      k++;
+    }
+  }
 
   /* Move non-local gparts to the end of the list. */
-  for (int k = 0; k < nr_gparts; k++)
+  for (int k = 0; k < nr_gparts;) {
     if (cells[gind[k]].nodeID != local_nodeID) {
       cells[gind[k]].gcount -= 1;
       nr_gparts -= 1;
@@ -472,6 +477,11 @@ void space_rebuild(struct space *s, double cell_max, int verbose) {
       gind[k] = gind[nr_gparts];
       gind[nr_gparts] = t;
     }
+    else {
+      /* Increment when not exchanging otherwise we need to retest "k".*/
+      k++;
+    }
+  }
 
   /* Exchange the strays, note that this potentially re-allocates
      the parts arrays. */
-- 
GitLab