Hello, I have been looking for a way to build an array dynamically and it seems that the way is:
int main(){
int **mat;
int filas = 2, columnas = 3; /*Supongamos esos valores*/
mat = (int **)malloc(filas * sizeof(int *));
for(i = 0; i < columnas; i++)
mat[i] = (int *)malloc(columnas * sizeof(int));
However, I can't find how to free the memory allocated to the array. Is it just done free(mat)
or does it have to be done free(mat[i])
for each row and after free(mat)
?
You must use
free()
to free the memory of each of the elements that you have created withmalloc
. That would bemat
and the differentmat[i]
ones inside the loop.But what really matters is the order in which you do it . If they were
malloc
independent, you could dofree
regardless of the order; but in the array code, you have amalloc
that reserves space for a "list of pointers" (mat
) to other memory areas also reserved withmalloc
(mat[i]
). There is a dependency between them. If you were to make afree
from the initial pointer (mat
) then the other reserves you have made withmalloc
would be orphaned with no way to access or release them. That's why, in this case, you should free the memory in the reverse order that it was allocated: first themat[i]
inside a loop and finallymat
.Something like this: