From 59060fec1b8008d1a41c1da684c293fd6a3a7690 Mon Sep 17 00:00:00 2001
From: Rahil Doshi <rahil.doshi@fau.de>
Date: Fri, 28 Feb 2025 18:41:55 +0100
Subject: [PATCH] Add bounds check to prevent out-of-bounds access. Ensure
 idx_E_neq can't exceed size-2 for safe interpolation.

---
 .../include/interpolate_double_lookup_cpp.h   | 21 ++++++-------------
 1 file changed, 6 insertions(+), 15 deletions(-)

diff --git a/src/pymatlib/core/cpp/include/interpolate_double_lookup_cpp.h b/src/pymatlib/core/cpp/include/interpolate_double_lookup_cpp.h
index 5e2f009..d1f3b6a 100644
--- a/src/pymatlib/core/cpp/include/interpolate_double_lookup_cpp.h
+++ b/src/pymatlib/core/cpp/include/interpolate_double_lookup_cpp.h
@@ -8,21 +8,6 @@ double interpolate_double_lookup_cpp(
     double E_target,
     const ArrayContainer& arrs) {
 
-    const size_t n = arrs.T_eq.size();
-    if (n != arrs.E_neq.size() || n < 2) {
-        throw std::runtime_error("Invalid array sizes");
-    }
-
-    // Determine array order
-    const bool is_ascending = arrs.T_eq[0] < arrs.T_eq[n-1];
-    const size_t start_idx = is_ascending ? 0 : n-1;
-    const size_t end_idx = is_ascending ? n-1 : 0;
-
-    // Validate energy density increases with temperature
-    if (arrs.E_neq[start_idx] >= arrs.E_neq[end_idx]) {
-        throw std::runtime_error("Energy density must increase with temperature");
-    }
-
     // Handle boundary cases
     if (E_target <= arrs.E_neq[0]) return arrs.T_eq[0];
     if (E_target >= arrs.E_neq.back()) return arrs.T_eq.back();
@@ -34,7 +19,13 @@ double interpolate_double_lookup_cpp(
     // Get index from mapping
     int idx_E_neq = arrs.idx_map[idx_E_eq];
 
+    // Make sure we don't go out of bounds
+    idx_E_neq = std::min(idx_E_neq, static_cast<int>(arrs.E_neq.size() - 2));
+
     // Adjust index if needed
+    /*if (arrs.E_neq[idx_E_neq + 1] < E_target) {
+        ++idx_E_neq;
+    }*/
     idx_E_neq += arrs.E_neq[idx_E_neq + 1] < E_target;
 
     // Get interpolation points
-- 
GitLab