multiholle
multiholle

Reputation: 3170

Correct allocate and free memory for arrays in C++

I'm dealing with dynamic arrays. The function empty_matrix() creates a new array, representing a matrix. delete_matrix() frees all memory, allocated for the matrix.

Do I get a memory leak in function example() if I call add(add(a, b), c)? What will happen to the memory allocated in the function add(...)? Do I have to free it? Where should I do it?

 matrix empty_matrix(int dim) {
 matrix m;
 m.dim = dim;
 m.data = new int*[dim];
 for (int i = 0; i < dim; i++)
  m.data[i] = new int[dim];

 return m;
}

void delete_matrix(matrix m) {
 for (int i = 0; i < dim; i++)
  delete [] m.data[i];
 delete [] m.data;
}

matrix add(matrix a, matrix b) {
 matrix c = empty_matrix(a.dim);
 for (int i = 0; i < a.dim; i++)
  for (int j = 0; j < a.dim; j++)
   c.data[i][j] = a.data[i][j] + b.data[i][j];

 return c;
}

void example() {
 matrix a = empty_matrix(100);
 matrix b = empty_matrix(100);
 matrix c = empty_matrix(100);

 // some modifications of a, b and c
 // ...

 matrix d = add(add(a, b), c);
 print_matrix(d);

 delete_matrix(a);
 delete_matrix(b);
 delete_matrix(c);
 delete_matrix(d);
} 

Upvotes: 2

Views: 4839

Answers (3)

Kos
Kos

Reputation: 72319

You should have exactly one new for one delete and one new[] for one delete[] in your code. That's the most important principle.

Hence, if the function add creates a new matrix, it needs to be deleted somewhere.


Also, empty_matrix should be the constructor of the matrix class, and delete_matrix should be its destuctor.

You could also replace the data with a std::vector and your memory handling would be much more automated, relieving you from the necessity of counting news and deletes.

Upvotes: 1

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133122

What you should do is use Object Orientation/RAII. Your data member of matrix class should be private, and memory for it should be allocated in the constructor, and freed in the destructor. This way, you won't have to worry about memory leaks.

For example...

class matrix
{
public:
      typedef int element_type;
      matrix(int dimension)
          :data_(new element_type[dimension*dimension])
      {

      }  
      //Do define your copy-constructor and assignment operators
      ~matrix()
      {
         delete [] data_;
      } 

private:
      element_type* data_;
};

This all, of course, if this is homework. If it is not, then you should refrain from using arrays in this situation. Use std::vectors

Upvotes: 5

St&#233;phan Kochen
St&#233;phan Kochen

Reputation: 19943

Yes, you will have to free the result of any empty_matrix or add call using delete_matrix. You're leaking memory, because you're not freeing the matrix of the innermost add call.

Upvotes: 2

Related Questions