ShaolinGOD - 3 months ago 20

C Question

I have this function to allocate memory to a matrix:

`double **mmalloc(int r, int c){`

double **matrix = (double **)malloc((r)*sizeof(double*));

for (int y = 0; y < r; y++){

matrix[y] = (double *)malloc(c*sizeof(double));

}

for (int y = 0; y < r; y++){

for(int x = 0; x < c; x++){

matrix[y][x] = 0;

}

}

return matrix;

}

How would I free all the memory of the returned matrix? I have this function to free the matrix... I can free the rows of the matrix but I cant free the columns.

Here's the freeing function:

`// Free all memory allocated for A`

void mfree(int r, int c, double **A){

for (int y = 0; y < r; y++){

free(A[y]);

}

}

Answer

You need to free all rows one by one, then the initially allocated column (that contains all rows)

```
void xfree(int r, int c, double **A){
for (int y = 0; y < r; y++){
free(A[y]);
}
free (A);
}
```

in this order.

```
double ** (Initial allocation)
↓
(double *)row0 → col0 col1 ...
(double *)row1 → col0 col1 ...
...
```

where each `row`

*i* is made of (double) columns.

In order to completely free a dynamically allocated array of arrays, keep these rules in mind

the number of

*free*s has to equal the number of*malloc*s that was used to allocate the array and its arraysconsider that if something is

*free*d it is not usable anymore, even if it may work by chance (the behavior that follows such action is said Undefined Behavior). For example, if you`free(A)`

first, you shouldn't`free(A[i])`

since`A`

- a memory space that contains a list of pointers - is not supposed to be allocated/usable anymore.therefore

*free*first the innermost elements ("contained", eg`A[i]`

) then*free*the "containers" (eg`A`

).