Segfault in a matrix code using new
I created a simple class in C++ which has a private dynamic array. In the constructor I initialize the array using new and in the destructor I f开发者_JS百科ree it using delete.
When I instantiate the class using Class a = Class(..); it works as expected, however it seems I cannot instantiate it using the new operator (Like Class *a = new Class(..);), I always get a segmentation fault.
What I don't understand is when I should use new to instantiate a class and when just call the constructor or should it be possible to instantiate a class either with new or by just calling the constructor.
float** A = new float*[3];
for (int i=0; i<3; i++) {
A[i] = new float[3];
}
A[0][0] = 3; A[0][1] = 3; A[0][2] = 4;
A[1][0] = 5; A[1][1] = 6; A[1][2] = 7;
A[2][0] = 1; A[2][1] = 2; A[2][2] = 3;
Matrix *M = new Matrix(A, 3, 3);
delete[] A;
delete M;
Below the class definition..
class Matrix
{
private:
int width;
int height;
int stride;
float* elements;
public:
Matrix(float** a, int n, int m);
~Matrix();
};
Matrix::Matrix(float** a, int n, int m)
{
// n: num rows
// m: elem per rows
elements = new float[n*m];
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
elements[i*n + j] = a[n][m];
}
}
}
Matrix::~Matrix()
{
delete[] elements;
}
Replace i*n + j
by i*m + j
.
and replace a[n][m]
by a[i][j]
精彩评论