I've problem with easy C++ program which finds the largest submatrix in given matrix:
int *A = new int[n*m];
... setting fields for matrix, finding the largest one and etc
... r := size of square-submatrix, max_i := row, max_j := column of the largest
for (i = max_i; i < max_i + r; i++)
{
for (j = max_j; j < max_j + r; j++)
cout << A[i * n + j] << "\t";
cout << "\n";
}
<memory free>
end of program
Everything works great (so it's not problem with logic) - finding correct submatrix, prinitng etc.
Unexpectedly (or due to late night) when I put in memory free line delete[] A or delete everything crushes down with errors (but it's still printing result correctly - so the error must be in this line). I've tried set it to NULL and every combination. What goes wrong?
Thanks in advance
EDIT:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int i,j,k;
int m,n;
int r;
cout << "Size of matrix: \nRows: ";
cin >> n;
cout << "Columns: ";
cin >> m;
int *A = new int[n*m];
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
A[n*i + j] = rand() % 19 - 9;
cout << A[n*i + j] << "\t";
}
cout << "\n";
}
cout << "Size of submatrix: ";
cin >> r;
int liczba_kwadratow = (m + 1 -r) * (n+1 -r);
int max = -10000;
int max_i = 0;
int max_j = 0;
int row_iter = 0;
int col_iter = 0;
for (k = 0; k <liczba_kwadratow; k++)
{
int sum = 0;
for ( i = row_iter; i < row_iter + r; i++)
for ( j = col_iter; j < col_iter + r; j++)
sum += A[i * n + j];
if ( sum > max )
{
max = sum;
max_i = row_iter;
max_j = col_iter;
}
col_iter++;
if ( row_iter + r > m )
{
row_iter++;
col_iter = 0;
}
}
cout << "Field of the largest submatrix " << r << " of " << r << " equals " << max << "\n";
for (i = max_i; i < max_i + r; i++)
{
for (j = max_j; j < max_j + r; j++)
cout << A[i * n + j] << "\t";
cout << "\n";
}
...works great without delete[] A or delete A
}
asserts to make sure you are not perform any out-of-bound access, or better yet, use astd::vectorand member functionat()to perform the access. This way, if you attempt to access out-of-bounds, an exception is being thrown (this is not the case if you simply usestd::vector::operator[]). If you use such a vector, can easily test what's going on. And as a general rule, you should try avoiding using raw pointers in modern C++.imultipled by the stride of a row. you're multiplying by the height of a column.i*m+jshould be your index value.nshould only appear in those loops in one place: the top<limit foriin the outer-for-loop.