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);
}
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…
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