C: Correctly freeing memory of a multi-dimensional array

OK, there’s a fair deal of confusion explaining exactly what order the
necessary free() calls have to be in, so I’ll try to clarify what
people are trying to get at and why.

Starting with the basics, to free up memory which has been allocated
using malloc(), you simply call free() with exactly the pointer
which you were given by malloc(). So for this code:

int **a = malloc(m * sizeof(int *));

you need a matching:

free(a);

and for this line:

a[i]=malloc(n * sizeof(int));

you need a matching:

free(a[i]);

inside a similar loop.

Where this gets complicated is the order in which this needs to happen. If
you call malloc() several times to get several different chunks of
memory, in general it doesn’t matter what order you call free() when
you have done with them. However, the order is important here for a very
specific reason: you are using one chunk of malloced memory to hold
the pointers to other chunks of malloced memory. Because you must
not attempt to read or write memory once you have handed it back with
free(), this means that you are going to have to free the chunks with
their pointers stored in a[i] before you free the a chunk itself.
The individual chunks with pointers stored in a[i] are not dependent on each
other, and so can be freed in whichever order you like.

So, putting this all together, we get this:

for (i = 0; i < m; i++) { 
  free(a[i]);
}
free(a);

One last tip: when calling malloc(), consider changing these:

int **a = malloc(m * sizeof(int *));

a[i]=malloc(n * sizeof(int));

to:

int **a = malloc(m * sizeof(*a));

a[i]=malloc(n * sizeof(*(a[i])));

What’s this doing? The compiler knows that a is an int **, so it can
determine that sizeof(*a) is the same as sizeof(int *). However, if
later on you change your mind and want chars or shorts or longs or
whatever in your array instead of ints, or you adapt this code for later
use in something else, you will have to change just the one remaining
reference to int in the first quoted line above, and everything else
will automatically fall into place for you. This removes the likelihood
of unnoticed errors in the future.

Good luck!

Leave a Comment