mjswartz mjswartz - 2 months ago 7
C Question

Free specific type of memory allocation in C

I've found an interesting way to allocate matrices in C which allows the use of

[i][j]
without initializing as
double matrix_a[nrows][ncols]
. The allocation is

double (*matrix_a)[ncols] = (double (*)[ncols])malloc(sizeof(double) * (nrows) * (ncols));


But I can't find how to properly free this type of allocation. Would it be as simple as
free(matrix_a)
?

Answer

That is correct. You may only pass to free what was returned from malloc and family. So since you did one malloc, you do one free.

Also, there is no need to cast the return value of malloc:

double (*matrix_a)[ncols] = malloc(sizeof(double) * (nrows) * (ncols));
Comments