From 98e4ebc932ada852f84e2c9cb83cf6533a3f27f9 Mon Sep 17 00:00:00 2001
From: Xavier Robin <xavier.robin@unibas.ch>
Date: Wed, 29 Mar 2023 14:38:57 +0200
Subject: [PATCH] fix: guard against invalid handles

GetPrev() or GetNext() may return invalid residue handles. It is
unclear what happens next, find() may simply (hopefully) find nothing,
however this feels unsafe. This fix guards against this possibility
by checking for handles validity before giving them to find().
---
 modules/mol/base/src/transfer_connectivity.cc | 34 +++++++++++--------
 1 file changed, 19 insertions(+), 15 deletions(-)

diff --git a/modules/mol/base/src/transfer_connectivity.cc b/modules/mol/base/src/transfer_connectivity.cc
index 448fde12e..4f50390cc 100644
--- a/modules/mol/base/src/transfer_connectivity.cc
+++ b/modules/mol/base/src/transfer_connectivity.cc
@@ -110,24 +110,28 @@ public:
     }
     // educated guess: we are trying to connect to the previous/next residue
     std::map<ResidueHandle, ResidueHandle>::const_iterator j;
-    j = to_from_->find(dst_res.GetPrev());
-    if (j != to_from_->end()) {
-      if (j->second == r) {
-        if (CheckInsertionCode(
-                              j->first.FindAtom(src_atom.GetName()).GetResidue(),
-                              r, dst_res)) {
-          return j->first.FindAtom(src_atom.GetName());
+    if (dst_res.GetPrev().IsValid()) {
+      j = to_from_->find(dst_res.GetPrev());
+      if (j != to_from_->end()) {
+        if (j->second == r) {
+          if (CheckInsertionCode(
+                                j->first.FindAtom(src_atom.GetName()).GetResidue(),
+                                r, dst_res)) {
+            return j->first.FindAtom(src_atom.GetName());
+          }
         }
       }
     }
-    j = to_from_->find(dst_res.GetNext());
-    if (j != to_from_->end()) {
-      if (j->second == r) {
-        if (CheckInsertionCode(
-                              j->first.FindAtom(src_atom.GetName()).GetResidue(),
-                              r, dst_res)) {
-            return j->first.FindAtom(src_atom.GetName());
-          }
+    if (dst_res.GetNext().IsValid()) {
+      j = to_from_->find(dst_res.GetNext());
+      if (j != to_from_->end()) {
+        if (j->second == r) {
+          if (CheckInsertionCode(
+                                j->first.FindAtom(src_atom.GetName()).GetResidue(),
+                                r, dst_res)) {
+              return j->first.FindAtom(src_atom.GetName());
+            }
+        }
       }
     }
     // still nothing. scan linearly through all residues.
-- 
GitLab