views:

345

answers:

5

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);
}
+3  A: 

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);
Arkaitz Jimenez
+4  A: 

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
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
Isn't that another way of saying reverse?
GMan
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
+3  A: 

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.

Pavel Shved
Why do you have to reverse the order in the loop?
Kinopiko
Because a[1] was allocated after a[0], so you should deallocate a[1] first.
Pavel Shved
Why do you need to free a[1] before a[0] ? They are different malloced chunks, there is no dependency between them
Arkaitz Jimenez
Who said that "you need to"? I think it just looks... sane.
Pavel Shved
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
I'm pretty sure most people would release the array going forward, not backward.
Edan Maor
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
@Till: I justify nothing and I hope that some people are more flexible in perceiving the code they read.
Pavel Shved
A: 

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
how is this an answer to the question?
Blindy
Pavel Shved wrote the correct answer. I just wrote a comment with some code.
sambowry
You should write comments into the question's "comment" field. It also supports code blocks.
Johannes Schaub - litb
@litb: please copy my answer into a comment field of the question. Thank You.
sambowry
There's no reason for a down vote. I find the answer to many questions on SO is "you shouldn't do that, do this instead". There is room for answers to the letter of the question and answer to the meaning of the question.
jmucchiello
+14  A: 

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
+1 Excellent answer; thanks for explaining the issue about the'reverse order' and also the point about the doing `sizeof(*a)`
Andreas Grech
You're welcome. Feel free to accept it when you're ready.... :-)
Tim
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
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