views:

125

answers:

1

Hi all

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 free 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;
}
+4  A: 

Replace i*n + j by i*m + j. and replace a[n][m] by a[i][j]

Alexey Malistov
Thx, but doesn't solve the segfault I get..
Nils
Fixed. replace `a[n][m]` by `a[i][j]` or `a[j][i]`.
Alexey Malistov
you are right but n=m=3 in his example.
Anders K.
Argh!! Seems like i was a bit too tired when writing this.. Thank you! But it's still strange that it does not segfault when instantiating by just calling the constructor..
Nils
Btw is there an article somewhere which explains when to use new and when to just call the constructor?
Nils
This is basically a question of the object lifetime. Once you understand the basics of C++ (or even C) variable lifetime rules, the rest should be obvious.
Suma
@Nils, it is not strange. When you instantiate the class using `Class a = Class(..);` it works as expected because your `a` is on the stack. Stack memory is valid.
Alexey Malistov
May you suggest any literature?
Nils
I think it is more complicated. It works "by chance" - he is getting a buffer overflow, and depending on what is in the neighbouring memory he sees different "undefined behaviour".
Suma
Any good C/C++ primer book should do. Search and you will find.
Suma