Is here any memory leak?

I'm trying to make class to manipulate matrix. Can anyone tell me if here is any memory leak, or a better way to do this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  class matrix
{
private:
    int n;
    int** mat;
public:
    matrix(int sz);
    ~matrix();
    int*& operator[](int i) { return mat[i]; }
};

matrix::matrix(int sz)
{
    n = sz;
    mat = new int*[sz];

    for(int i = 0; i < sz; i++)
    {
        mat[i] = new int[sz];
    } // end of for
}

matrix::~matrix()
{
    for(int i = 0; i < n; i++)
    {
        delete []mat[i];
    } // end of for

    delete []mat;
}
You definitely need a custom copy assignment too.


This is a variation:
1
2
3
4
5
6
mat    = new int * [sz];
mat[0] = new int [sz*sz];

for ( int i = 1; i < sz; ++i ) {
  mat[i] = mat[0] + i*sz;
}

How is the variation working?!
Better?

1. There are less separate allocations.
2. The actual data of the array is on contiguous memory block, just like it were if it was a plain, statically allocated (2D) array.


The 'mat' in both versions is a pointer to array of sz pointers. Each of those sz pointers do point to somewhere.



PS. In your program, line 9, you do return a reference to a pointer. The caller can thus change the pointer to point elsewhere. Is that intentional and necessary?

PS2. You could overload the operator() to return reference to array element. Yes, syntax would be different, but wouldn't that emphasize that the matrix is an object?
1
2
3
4
5
matrix foo(42);

foo(3, 7) = 21;
//or
foo[3][7] = 21;
Okay, thanks...
Topic archived. No new replies allowed.