mjswartz mjswartz - 1 year ago 82
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

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

Answer Source

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download