mitsuki31 / jmatrix

A lightweight Java library for basic introduction to matrix and linear algebra concepts.
https://mitsuki31.github.io/jmatrix/
Apache License 2.0
1 stars 0 forks source link

[BUG]: Shallow copy issue in `getEntries()` method #103

Closed mitsuki31 closed 7 months ago

mitsuki31 commented 8 months ago

Description

The getEntries() method in the Matrix class currently returns a shallow copy of the internal ENTRIES array. This means that any modifications made to the returned array will directly affect the original data within the matrix object, potentially leading to unintended side effects and data corruption.

Reproduction Steps

  1. Create a Matrix object.
  2. Call getEntries() to obtain a reference to the array.
  3. Modify an element within the returned array.
  4. Observe that the corresponding element in the original matrix object has also been modified.
// Create a new matrix object
Matrix m = new Matrix(new double[][] {
    { 12, 12, 12 },
    { 13, 13, 13 }
});
double[][] entries = m.getEntries();  // Retrieve the entries

for (int i = 0; i < entries[0].length; i++) {
    // Modify the first row entries to 5.0 for each
    entries[0][i] = 5.0;
}

// Display and compare both objects
m.display();
Matrix.display(entries);

Output:

[   [5.0, 5.0, 5.0],
    [13.0, 13.0, 13.0]   ]
[   [5.0, 5.0, 5.0],
    [13.0, 13.0, 13.0]   ]

Expected Behavior

The getEntries() method should either:

Severity

Medium to high, depending on the potential impact of unintended modifications to matrix data in the application's context.

Solutions

  1. Implement Deep Copy:
    • Create a new array with the same dimensions as ENTRIES.
    • Iterate through ENTRIES and copy each element individually to the new array.
    • Return the new array.
  2. Consider Immutable Wrapper:
    • Create a wrapper class that exposes accessor methods for the array elements but prevents direct modification.
    • Return an instance of the wrapper class instead of the raw array.