简体   繁体   中英

Error: malloc: *** error for object 0x7f9edf504080: pointer being freed was not allocated

I am trying to get this code down for a class and deals with matrix but I keep getting the error:

malloc: *** error for object 0x7f9edf504080: pointer being freed was not allocated
malloc: *** set a breakpoint in malloc_error_break to debug

If anybody could help, it will be appreciated.

#include <iostream>
using namespace std;

class matrix {
    int **a;
public:
    matrix() {
        int i,j;
        a = new int*[3];
        for (i = 0; i <3; i++)
            a[i] = new int[3];
        cout << "Enter elements for 3x3 matrix: \n";
        for (i = 0;i <3; i++)
        for (j = 0;j <3; j++)
            cin >> a[i][j];
    }
    matrix (matrix &x) {
        int i,j;
        a = new int*[3];
        for (i = 0;i <3;i++)
            a[i] = new int[3];
        for (i = 0;i < 3; i++)
        for (j = 0;j < 3; j++)
            a[i][j] = x.a[i][j];
    }
    ~matrix() {
        int i;
        for (i = 0;i<3;i++)
            delete a;
    }

    void putinmatrix();
};

void matrix::putinmatrix() {
    int i,j;
    for (i = 0;i < 3;i++) {
        for(j = 0;j<3;j++)
            cout << a[i][j] <<" ";
        cout<<endl;
    }
}

int main() {
    matrix obj1;
    matrix obj2(obj1);
    cout<<"Matrix 1 and Matrix 2:\n";
    obj1.putinmatrix();
}

Your destructor is incorrect, you have four new[] in your constructor so there should be four delete[] in your destructor

~matrix() {
    for (int i = 0; i<3; i++)
        delete[] a[i];
    delete[] a;
}

See how the pattern of the delete[] is exactly the same as the pattern of the new[] (but in reverse)?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM