From 8f214f744cabfbf439c9e5876d77f4ebab3b17f2 Mon Sep 17 00:00:00 2001
From: Mark Olesen <Mark.Olesen@esi-group.com>
Date: Tue, 20 Jun 2023 08:40:07 +0200
Subject: [PATCH] BUG: UPstream::shutdown misbehaves with external
 initialisation (fixes #2808)

- freeCommmunicatorComponents needs an additional bounds check.
  When MPI is initialized outside of OpenFOAM, there are no
  UPstream communicator equivalents
---
 src/Pstream/mpi/UPstream.C | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/src/Pstream/mpi/UPstream.C b/src/Pstream/mpi/UPstream.C
index 7a5332ce810..89778956254 100644
--- a/src/Pstream/mpi/UPstream.C
+++ b/src/Pstream/mpi/UPstream.C
@@ -1129,7 +1129,17 @@ void Foam::UPstream::allocatePstreamCommunicator
 
 void Foam::UPstream::freePstreamCommunicator(const label communicator)
 {
-    if (communicator != 0)
+    // Not touching the first communicator (WORLD)
+    // or anything out-of bounds.
+    //
+    // No UPstream communicator indices when MPI is initialized outside
+    // of OpenFOAM - thus needs a bounds check too!
+
+    if
+    (
+        communicator > 0
+     && (communicator < PstreamGlobals::MPICommunicators_.size())
+    )
     {
         if (PstreamGlobals::MPICommunicators_[communicator] != MPI_COMM_NULL)
         {
-- 
GitLab