我正在编写一个程序,它在构造函数中创建2D动态数组并在析构函数中删除它。但是当我从任何函数返回此类的对象时,它会导致运行时错误。
错误:访问冲突读取位置0xDDDDDD1
#include <iostream>
#include <cstdlib>
using namespace std;
class Matrix {
private:
int **MyArray;
int row, col;
public:
Matrix(int r, int c) {
MyArray = new int*[r];
for (int i = 0; i < r; i++) {
MyArray[i] = new int[c];
}
row = r;
col = c;
}
Matrix test() {
Matrix Temp(row, col);
return Temp;
}
~Matrix() {
for (int i = 0; i < row; i++) {
delete[] MyArray[i];
}
delete[] MyArray;
}
};
int main() {
Matrix m(2, 2), m2(2, 2);
m.test();
system("pause");
}
在追踪错误时,我在删除Temp对象后遇到了错误。该程序还删除了另一个位置。
#include <iostream>
using namespace std;
class Matrix {
private:
int **MyArray;
int row, col;
static int count;
public:
Matrix(int r, int c) {
MyArray = new int*[r];
for (int i = 0; i < r; i++)
MyArray[i] = new int[c];
row = r;
col = c;
}
Matrix test() {
Matrix Temp(row, col);
cout << "Temp->" << &Temp << endl;
return Temp;
}
~Matrix()
{
cout << "deleting-> " << this << endl;
for (int l = 0; l < row; l++)
delete[] MyArray[l];
delete[] MyArray;
}
};
void main() {
Matrix m(2, 2), m2(2, 2);
cout << "m->" << &m << endl;
cout << "m2->" << &m2 << endl;
m.test();
}