@@ -836,8 +836,28 @@ namespace MML
836836 // The Householder vectors are stored in the lower triangle of QR
837837 QRSolver (const Matrix<Type>& a) : m(a.RowNum()), n(a.ColNum()), QR(a), c(n), d(n), sing(false ), num_reflections(0 )
838838 {
839+ // Validate input matrix dimensions
840+ if (m <= 0 || n <= 0 )
841+ throw MatrixDimensionError (" QRSolver: Matrix dimensions must be positive" , m, n, 1 , 1 );
839842 if (m < n)
840843 throw MatrixDimensionError (" QRSolver: Matrix must have m >= n (rows >= columns)" , m, n, m, n);
844+
845+ // Verify QR copy succeeded correctly - this catches potential static initialization issues
846+ if (QR.RowNum () != m || QR.ColNum () != n) {
847+ // Detailed error for debugging
848+ std::string msg = " QRSolver: Matrix copy validation failed. Input: " +
849+ std::to_string (a.RowNum ()) + " x" + std::to_string (a.ColNum ()) +
850+ " , m=" + std::to_string (m) + " , n=" + std::to_string (n) +
851+ " , QR: " + std::to_string (QR.RowNum ()) + " x" + std::to_string (QR.ColNum ());
852+ throw std::runtime_error (msg);
853+ }
854+
855+ // Verify vectors were initialized correctly
856+ if (static_cast <int >(c.size ()) != n || static_cast <int >(d.size ()) != n) {
857+ std::string msg = " QRSolver: Vector initialization failed. n=" + std::to_string (n) +
858+ " , c.size=" + std::to_string (c.size ()) + " , d.size=" + std::to_string (d.size ());
859+ throw std::runtime_error (msg);
860+ }
841861
842862 int i = 0 , j = 0 , k = 0 ;
843863 Type scale = Type{0 }, sigma = Type{0 }, sum = Type{0 }, tau = Type{0 };
@@ -897,7 +917,12 @@ namespace MML
897917 // For square matrices, handle the last diagonal element separately
898918 if (m == n)
899919 {
900- d[n - 1 ] = QR[n - 1 ][n - 1 ];
920+ // Debug: verify matrix dimensions before access
921+ if (n <= 0 || QR.RowNum () != m || QR.ColNum () != n) {
922+ throw MatrixDimensionError (" QRSolver internal error: matrix dimensions corrupted" ,
923+ QR.RowNum (), QR.ColNum (), m, n);
924+ }
925+ d[n - 1 ] = QR (n - 1 , n - 1 ); // Use operator() for bounds checking potential
901926 c[n - 1 ] = 0.0 ; // No Householder reflection for last column in square matrix
902927 if (d[n - 1 ] == 0.0 )
903928 sing = true ;
0 commit comments