C ++错误:使用动态数组时双重释放或损坏(fasttop)

时间:2016-03-10 20:07:43

标签: c++ arrays dynamic-allocation function-parameter

以下代码给出了一个错误:double free或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;
}

我认为问题是由于我的数组指针而发生的。 我不知道如何实施修复;请帮忙!

1 个答案:

答案 0 :(得分:0)

这部分不正确:

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

M1应该通过引用传递,否则在operator <<完成时调用析构函数。您可以通过在析构函数中添加print语句来验证这一点 此外,您的operator <<应该写入out,而不是cout

固定版本应如下所示:

// 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;
}