43

Say you have the following ANSI C code that initializes a multi-dimensional array :

int main()
{
      int i, m = 5, n = 20;
      int **a = malloc(m * sizeof(int *));

      //Initialize the arrays
      for (i = 0; i < m; i++) { 
          a[i]=malloc(n * sizeof(int));
      }

      //...do something with arrays

      //How do I free the **a ?

      return 0;
}

After using the **a, how do I correctly free it from memory ?


[Update] (Solution)

Thanks to Tim's (and the others) answer, I can now do such a function to free up memory from my multi-dimensional array :

void freeArray(int **a, int m) {
    int i;
    for (i = 0; i < m; ++i) {
        free(a[i]);
    }
    free(a);
}
Community
  • 1
  • 1
Andreas Grech
  • 105,982
  • 98
  • 297
  • 360
  • 2
    Terminology quibble: this is not what C usually calls a "multidimensional array". It's just the only way to use the syntax `a[i][j]`, while still allowing both dimensions to be unknown at compile time. The other kind of multidimensional array an array of arrays, instead of this array of pointers to (the first elements of) arrays. – Steve Jessop Nov 14 '09 at 18:12

5 Answers5

77

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!

Tim
  • 9,171
  • 33
  • 51
  • 2
    +1 Excellent answer; thanks for explaining the issue about the'reverse order' and also the point about the doing `sizeof(*a)` – Andreas Grech Nov 14 '09 at 11:08
  • 1
    Also, please correct me if I'm wrong, but would I be correct in saying that `sizeof(*a[i])` is equivalent to your `sizeof(*(a[i]))`, since the array notation `[]` have higher precedence than `*` ? – Andreas Grech Nov 14 '09 at 11:14
  • 1
    No, I think you're right. http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence However, I work on a rule of thumb that if I have to look it up, probably others reading my code would have to look it up as well, so to save them (and me, later) trouble, explicitly using brackets helps to clarify things and save time. That's just a personal preference, though. – Tim Nov 14 '09 at 11:19
9

Undo exactly what you allocated:

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

Note that you must do this in the reverse order from which you originally allocated the memory. If you did free(a) first, then a[i] would be accessing memory after it had been freed, which is undefined behaviour.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 2
    Saying that you have to free in reverse order might be misleading. You just have to free the array of pointers after the pointers themselves. – Andomar Nov 14 '09 at 10:22
  • 1
    Isn't that another way of saying reverse? – GManNickG Nov 14 '09 at 10:35
  • 2
    I think @Andomar means it doesn't matter what order you free the a[i]'s in, just that you have to free all of them before freeing a. In other words, you can free a[0] thru a[m-1] or a[m-1] thru a[0] or all the even a[]'s followed by the odds. But I'm also certain @GregH didn't *mean* you had to do the a[]'s in reverse order, especially given his code. – paxdiablo Nov 14 '09 at 10:51
4

You need to iterate again the array and do as many frees as mallocs for the pointed memory, and then free the array of pointers.

for (i = 0; i < m; i++) { 
      free (a[i]);
}
free (a);
Khaled Alshaya
  • 94,250
  • 39
  • 176
  • 234
Arkaitz Jimenez
  • 22,500
  • 11
  • 75
  • 105
3

Write your allocation operators in exactly reversed order, changing function names, and you'll be all right.

  //Free the arrays
  for (i = m-1; i >= 0; i--) { 
      free(a[i]);
  }

  free(a);

Of course, you don't have to deallocate in the very same reversed order. You just have to keep track on freeing same memory exactly once and not "forgetting" pointers to allocated memory (like it would have been if you free'd the a first). But deallocating in the reverse order is a good role of thumb to address the latter.

As pointed by litb in the comments, if allocation/deallocation had side-effects (like new/delete operators in C++), sometimes the backward order of deallocation would be more important than in this particular example.

Community
  • 1
  • 1
P Shved
  • 96,026
  • 17
  • 121
  • 165
  • Why do you have to reverse the order in the loop? –  Nov 14 '09 at 10:20
  • Because a[1] was allocated after a[0], so you should deallocate a[1] first. – P Shved Nov 14 '09 at 10:21
  • Why do you need to free a[1] before a[0] ? They are different malloced chunks, there is no dependency between them – Arkaitz Jimenez Nov 14 '09 at 10:25
  • Who said that "you need to"? I think it just looks... sane. – P Shved Nov 14 '09 at 10:32
  • 2
    Since `free` is without side effects in C (regarding your own program code), it doesn't seem to matter much. The "do it in reverse" rule is more important for languages that have a side effect attached to `free` and `alloc`, like C++ with its destructors/constructors. – Johannes Schaub - litb Nov 14 '09 at 10:57
  • 2
    I'm pretty sure most people would release the array going forward, not backward. – Edan Maor Nov 14 '09 at 11:00
  • Reversing the order of freeing the array-members is not needed, makes the code harder to read and understand. Justifying this step with a complete irrelavent example (C++ new / delete) is not helping either. – Till Nov 14 '09 at 13:26
  • @Till: I justify nothing and I hope that some people are more flexible in perceiving the code they read. – P Shved Nov 14 '09 at 14:02
1

I would call malloc() and free() only once:

#include <stdlib.h>
#include <stdio.h> 

int main(void){
  int i, m = 5, n = 20;
  int **a = malloc( m*(sizeof(int*) + n*sizeof(int)) );

  //Initialize the arrays
  for( a[0]=(int*)a+m, i=1; i<m; i++ ) a[i]=a[i-1]+n;

  //...do something with arrays

  //How do I free the **a ?
  free(a);

  return 0;
}
sambowry
  • 2,436
  • 1
  • 16
  • 13