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

Asked

Viewed 252 times

1

I am trying to create a library for operations with matrices in C++ but am running into a problem.

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

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

Follow the code below:

#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 go straight into 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;
}
  • 1

    In function vector<vector<double>> imprime(vector<vector<double>> X) { did not miss a Return? In fact it could not be void?

1 answer

1


You’re not returning anything, so there’s no point in having some kind of return there.

If you were to return, which is not necessary in the code presented, then you 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 getting the individual size is an error that is not the cause of the problem by demonstrating.

#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);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Wow, what a ditty I gave! That was exactly the problem, now it’s working right. Thank you so much! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.