C++ free (): invalid pointer aborted when trying to create a function

I'm trying to create a library for operations with arrays in C++ but I'm running into a problem.

I created a function to print on the screen a certain Matrix. The function even returns the expected values, however, the following error message appears on the last line:

free(): invalid pointer
Abortado Abortado (imagem do núcleo gravada)

Below is the Code:

#include<iostream>
#include<vector>

using namespace std;

vector<vector<double>> imprime(vector<vector<double>> X) {

    int linhas  = X.size();
    int colunas = X[0].size();

    for (int i=0; i<linhas; i++) {
        for (int j=0; j<colunas; j++) {
            cout << X[i][j] << "\t";
        }
        cout << endl;
    }
}

int main() {

vector<vector<double>> X {
        {1.0, 2.0, 3.0,2.5},
        {2.0, 5.0,-1.0,2.0},
        {-1.5,2.7,3.3,-0.8}
};

imprime(X);

return 0;
}

When I try to make the Loop be direct in the main function, it works:

#include<iostream>
#include<vector>

using namespace std;

int main() {

vector<vector<double>> X {
        {1.0, 2.0, 3.0,2.5},
        {2.0, 5.0,-1.0,2.0},
        {-1.5,2.7,3.3,-0.8}
};

for (int i=0; i<X.size(); i++) {
        for (int j=0; j<X[0].size(); j++) {
            cout << X[i][j] << "\t";
        }
        cout << endl;
    }

return 0;
}
Author: Maniero, 2020-05-15

1 answers

You're not returning something, so you don't have to have a return type there.

If it were to return, which is not necessary in the code presented, then it would have to have a return in the code.

There is a conceptual error there that works in this case but nothing guarantees that all columns will have the same size, so taking the individual size is an error that is not the cause of the problem demostrando.

#include<iostream>
#include<vector>
using namespace std;

void imprime(vector<vector<double>> X) {
    int linhas  = X.size();
    for (int i = 0; i < linhas; i++) {
        int colunas = X[0].size();
        for (int j = 0; j < colunas; j++) cout << X[i][j] << "\t";
        cout << endl;
    }
}

int main() {
    vector<vector<double>> X {
            {1.0, 2.0, 3.0,2.5},
            {2.0, 5.0,-1.0,2.0},
            {-1.5,2.7,3.3,-0.8}
    };
    imprime(X);
}

See working on ideone. And no repl.it. also I put on GitHub for future reference .

 1
Author: Maniero, 2020-05-18 13:52:45