Reputation: 6150
I have a function which creates a 2D array:
float** createMatrix(int x, int y){
float** array= malloc(sizeof(float*) * y);
for(int i=0; i<y; i++)
array[i] = malloc(sizeof(float) * x);
return array;
}
Now I can create a 2D array:
float** temp=createMatrix(2,2);
I also have a function, for e.g., which transposes my "matrix" (2D array):
float** matrixTranspose(float** m, int x, int y){
float** result=createMatrix(y, x);
for(int i=0; i<y; i++){
for(int j=0;j<x; j++) result[j][i]=m[i][j];
}
return result;
}
Now if I do this:
temp=matrixTranspose(temp,2,2);
what happens with the old memory previously allocated to temp? My transpose function allocates new memory chunk. Obviously I would have to somehow free "old temp" after the Transposition, but how (elegantly)?
Upvotes: 1
Views: 165
Reputation: 373
int FreeMatrix(char **matrix, int x, int y) {
int i;
for(i=0; i<y; i++) {
free(matrix[i]);
}
free(matrix);
}
The not-so-elegant part, here, is that you have to keep track of the allocated ranges. There are various ways to handle this, most involve keeping track of them, e.g. by wrapping malloc and free. Google for 'malloc free multidimensional arrays'.
Upvotes: 0
Reputation: 59607
Your free
can mirror your allocation:
int i;
for(i = 0; i < y; i++)
free(array[i]);
free(array);
But if you assign to temp
the new matrix created by matrixTranspose
, then you'll lose your pointer to that memory. So keep track of that with another pointer, or assign the result of matrixTranspose
to another pointer:
float **transposedMatrix = matricTranspose(...);
If you consider your matrices as mutable, you could also transpose them in place: rather than allocating a new matrix in the matrixTranspose
function, you move around the numbers in the existing array. You can do this in place with one float temp
.
Upvotes: 3
Reputation:
You don't do this. You're gonna need two variables for this.
float **tmp2 = matrixTranspose(temp, 2, 2);
and write a deallocator function for the matrix:
void freeMatrix(float **m, int x) {
int i;
for (i = 0; i < x; i++) {
free(m[i]);
}
free(m);
}
and only then you can assign
temp = tmp2;
Upvotes: 1
Reputation: 38153
Use another variable (pointer), when calling matrixTranspose
. Then, write a function for free
-ing memory of a matrix.
Like this:
float** newTemp = matrixTranspose(temp,2,2);
freeMatrix( temp );
temp = newTemp;
Otherwise, you'll loose the memory, pointed by temp
and thus you have a memory leak.
freeMatrix
should be symmetric to the allocating memory:
for(int i=0; i<y; i++)
free( array[i] );
free( array );
Upvotes: 2