Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

C: Correctly freeing memory of a multi-dimensional array

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...