From 9e222734a8a7cfae28792bcfd311e955caf6eac8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Villemot?= Date: Wed, 27 Nov 2019 16:54:01 +0100 Subject: [PATCH] Bytecode: fix logic in routine that substracts two sparse matrices The logic of the dynSparseMatrix::Sparse_substract_SA_SB() routine was incorrect. In some cases, it would read past the last nonzero elements of the A matrix, and consequently write past the number of allocated nonzero elements of the C matrix. This would lead to crashes and, probably, to wrong results under certain circumstances. Closes: #1652 --- mex/sources/bytecode/SparseMatrix.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mex/sources/bytecode/SparseMatrix.cc b/mex/sources/bytecode/SparseMatrix.cc index 1f4cb7fb6..322b6943f 100644 --- a/mex/sources/bytecode/SparseMatrix.cc +++ b/mex/sources/bytecode/SparseMatrix.cc @@ -2618,7 +2618,7 @@ dynSparseMatrix::Sparse_substract_SA_SB(mxArray *A_m, mxArray *B_m) C_j[A_col+1] = nze_C++; C_col = A_col; } - else if (A_row < B_row || (nze_B >= total_nze_B && nze_A < total_nze_A)) + else if ((A_row < B_row && nze_A < total_nze_A) || nze_B == total_nze_B) { C_d[nze_C] = A_d[nze_A++]; C_i[nze_C] = A_row; @@ -2637,7 +2637,7 @@ dynSparseMatrix::Sparse_substract_SA_SB(mxArray *A_m, mxArray *B_m) C_col = B_col; } } - else if (A_col < B_col || (nze_B >= total_nze_B && nze_A < total_nze_A)) + else if ((A_col < B_col && nze_A < total_nze_A) || nze_B == total_nze_B) { C_d[nze_C] = A_d[nze_A++]; C_i[nze_C] = A_row;