So I have a class called MatrixMxN, in the constructor it has parameters row, column. I am attempting to allocate memory for a 2D array with dimensions row, column, although I am getting a problem with doing this..
(I am overriding the parenthesis operator to assign values to each entry)
{
MatrixMxN coord(4, 1);
coord(0, 0) = 1.0;
coord(0, 1) = 1.0;
coord(0, 2) = 1.0;
coord(0, 3) = 1.0;
}
The problem I am facing seems to be when the deconstructor is called and I receive the error:-
Windows has triggered a breakpoint in MatrixTest.exe.
This may be due to a corruption of the heap, which indicates a bug in MatrixTest.exe or any of the DLLs it has loaded.
The snippet from my matrix class is as follows;
typedef float* floatPtr;
class MatrixMxN {
private:
float** entry;
int rows;
int cols;
public:
MatrixMxN(int r, int c) {
rows = r;
cols = c;
//Create a matrix
if(rows > 0 && cols > 0) {
//Declare an array of pointers
entry = new floatPtr[rows];
//Declare each array
for(int i=0; i<rows; i++) {
entry[i] = new float[cols];
}
this->empty();
}
}
~MatrixMxN() {
//Free memory
for(int i=0; i<rows; i++) {
delete[] entry[i];
}
//Free pointers array
delete[] entry;
}
void empty() {
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
entry[i][j] = 0;
}
}
}
// Assignment operator
void operator=(MatrixMxN& other) {
//Check they are the same size
assert(rows == other.rows && cols == other.cols);
//Copy
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
entry[i][j] = other(i, j);
}
}
}
float& operator()(const int irow, const int icol) {
//Check they are not out of bounds
assert ( (irow >= 0 && irow < rows) || (icol >= 0 && icol < cols) );
return entry[irow][icol];
}
...
The part which is tripping up an error is in the deconstructor inside the loop;
//Free memory
for(int i=0; i<rows; i++) {
delete[] entry[i];
}
The dbgheap.c file throws the error on the first attempt to delete[] entry[i] where i =0. Although when printing the matrix it works fine as intended but there appears to be an error here. Hopefully I have provided enough information here, thanks.
Edit1: Included assignment operator overload
Edit2: Included () overload
Answer:
The problem was I was entering the values in a transpose manner rather than how I had it. The memory was being corrupted here, thanks for all the help.
This may not be the cause but there is no copy constructor or assignment operator defined for the class
MatrixMxN: either define them or make the object non-copyable by declaring themprivate.While not the problem in this example,
delete[]will be invoked on an uninitialized pointers in the destructor ifrows > 0butcols <= 0. In the constructor,entryis only initalized ifrows > 0 && cols > 0. Ifrows > 0butcols <= 0the followingforloop in the destructor still invokesdelete[] entry[i];:followed by:
EDIT:
This
assertinoperator()is incorrect:it should be using
&&: