Skip to content

Commit

Permalink
check integer overflow in Matrix::setSize (#296)
Browse files Browse the repository at this point in the history
* check integer multiplication overflow

* overflow check from a constructor function.

* style fix

* print error message correction
  • Loading branch information
dreamer2368 authored Aug 8, 2024
1 parent 48f21d5 commit 98eda96
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/linalg/Matrix.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ Matrix::Matrix(
memcpy(d_mat, mat, d_alloc_size*sizeof(double));
}
else {
// Check integer multiplication overflow
if (num_rows > INT_MAX / num_cols)
CAROM_ERROR("Matrix::Matrix- new size exceeds maximum integer value!\n");

d_mat = mat;
d_alloc_size = num_rows*num_cols;
d_num_cols = num_cols;
Expand Down
5 changes: 5 additions & 0 deletions lib/linalg/Matrix.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include <complex>
#include <memory>
#include <string>
#include <climits>

namespace CAROM {

Expand Down Expand Up @@ -149,6 +150,10 @@ class Matrix
int num_rows,
int num_cols)
{
// Check integer multiplication overflow
if (num_rows > INT_MAX / num_cols)
CAROM_ERROR("Matrix::setSize- new size exceeds maximum integer value!\n");

int new_size = num_rows*num_cols;
if (new_size > d_alloc_size) {
if (!d_owns_data) {
Expand Down

0 comments on commit 98eda96

Please sign in to comment.