0

The following code gives me an error: double free or corruption (fasttop):

class Matrix{
    public:
        Matrix();
        Matrix(int size, int *&a);
        ~Matrix();
        friend ostream &operator <<(ostream &out, const Matrix M1);
    private:
        int size;
        int *array;
};

//This function is a constructor with parameters.
Matrix::Matrix(int Size, int *&a){
    size = Size;
    array = new int[size];
    for (int i = 0;i<size;i++)
        array[i] = a[i];
}

//This function is the destructor.
Matrix::~Matrix(){
    delete [] array;
}

//This function displays a matrix.
ostream & operator <<(ostream &out, const Matrix M1){
    for (int i=0;i<(M1.size);i++)
        cout << M1.array[i] << "\t ";
    return out;
}

int main(){
    int *A = new int[9];        //Creates pointer that points to a dynamicall created array.
    for (int i=0;i<9;i++)       //Populates array.
        A[i] = i + 1;
    Matrix m1(9, A);            //Constructs Matrix obj. m1 by passing through the pointer.
    cout << "M1:" << endl << m1 << endl;        //Prints out the array.
    cout << "M1:" << endl << m1 << endl;        //Prints out the array, but gives a different output from the first.
    return 0;
}

I think the problem is happening because of my array pointer. I don't know how to implement a fix; please help!

Screthan
  • 1
  • 2

1 Answers1

0

This part is incorrect:

ostream & operator <<(ostream &out, const Matrix M1){
    for (int i=0;i<(M1.size);i++)
        cout << M1.array[i] << "\t ";
    return out;
}

M1 should be passed by reference, otherwise the destructor is called when operator << completes. You can verify this by adding a print statement inside your destructor.
Additionally, your operator << should be writing to out, not cout.

The fixed version should look like this:

// Be sure to update your prototype as well!
ostream & operator <<(ostream &out, const Matrix &M1){
    for (int i=0;i<(M1.size);i++)
        out << M1.array[i] << "\t ";
    return out;
}
Mr. Llama
  • 20,202
  • 2
  • 62
  • 115
  • Thank you! This has fixed the issue. – Screthan Mar 10 '16 at 21:16
  • 1
    @Screthan - If this answer helped solve your problem, please consider [marking it as accepted](https://stackoverflow.com/help/someone-answers) using the check mark under the voting arrows. Thank you! – Mr. Llama Mar 10 '16 at 21:16