Can't understand reason of the SIGTRAP in c++ code

0

I am writing some function for work with matrix. I received correct output:

__11111111
__11111111
__333333333
__444444444444

But then program didn't stop and return invalid code

Process finished with exit code -1073741819 (0xC0000005)

How can i fix the error?

I tried debugger (gdb) and found out this:

Signal = SIGTRAP

And debugger presented me file new_allocator.h (attempt to deallocate nullptr)

 // __p is not permitted to be a null pointer.
      void
      deallocate(pointer __p, size_type)
      { ::operator delete(__p); }

My code

#include <bits/stdc++.h>

using namespace std;

#define EPS 0.000001

int dualMatrix(vector<vector<double>> a) {
    int n = a.size();
    int m = a[0].size();

    for (int col=0, row=0; col<m && row<n; ++col) {
        int sel = row;
        for (int i=row; i<n; ++i)
            if (abs (a[i][col]) > abs(a[sel][col]))
                sel = i;
        if (abs(a[sel][col]) < EPS)
            continue;
        for (int i=col; i<=m; ++i)
            swap(a[sel][i], a[row][i]);

        cout << "__11111111\n";
        for (int i=0; i<n; ++i)
            if (i != row) {
                if (a[row][col] == 0) {
                    cout << "DIVIDER IS ZERO" << endl;
                    return  -1;
                }
                double c = a[i][col] / a[row][col];
                for (int j=col; j<=m; ++j)
                    a[i][j] -= a[row][j] * c;
            }
        ++row;
    }
    int rank = 0;
    for (int i = 0; i < n; ++i) {
        double temp = a[i][i];
        if (temp == 0) {
            cout << "Diagonal element is 0 at the row=" << i << endl;
            rank = i;
            break;
        }
        for (int j = 0; j < m; ++j) {
            a[i][j] /= temp;
        }
    }
    cout << "__333333333\n";
    //printMatrix(a);
    cout << "__444444444444\n";
    return 0;
}

int main() {
    vector<vector<double>> tmp {{1, 2, 3}, {3, 4, 5}};
    dualMatrix(tmp);
    cout << "__END" << endl;
    return 0;
}
c++
asked on Stack Overflow Apr 23, 2020 by mascai • edited Apr 23, 2020 by KamilCuk

1 Answer

3
int m = a[0].size();

The size of the vector is m

for (int i=col; i<=m; ++i)
    swap(a[sel][i], a[row][i]);

Here, i is outside the bounds of the vectorsa[sel] and a[row]. Accessing the vector outside of its bounds with the subscript operator has undefined behaviour.

Same here:

for (int j=col; j<=m; ++j)
    a[i][j] -= a[row][j] * c;

How can i fix the error?

Don't access the vector outside of its bounds. If the size of the vector is 3, then the valid indices are 0, 1 and 2. If the size if m, then valid indices are 0, ..., m - 1

answered on Stack Overflow Apr 23, 2020 by eerorika • edited Apr 23, 2020 by eerorika

User contributions licensed under CC BY-SA 3.0