Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which order should allocated memory blocks be freed in?

Given something like:

char *a = malloc(m);
char *b = malloc(n);
char *c = malloc(o);

Once you have finished with the blocks of memory, this is correct:

free(a);
free(b);
free(c);

And so is this:

free(c);
free(b);
free(a);

Yet one or other order must be used, and it is more satisfying to have a basis for choosing one.

Is there any existing implementation on which it makes any difference to memory fragmentation, or to the speed at which the memory is freed and subsequent allocation requests satisfied? If so, which order is more efficient? Or is there any other basis for choosing an order?

like image 772
rwallace Avatar asked Sep 03 '25 16:09

rwallace


1 Answers

Without any known relationship between these blocks of memory, there is no basis for designating which deallocation order is correct. Just as there is no basis for deciding which allocation order is correct.

This is not a question that can be answered a priori. The only reason not to deallocate memory is if you're still using it, and one piece of memory could be "using" (ie: storing a pointer into) another. So without knowing anything about what is going on inside of that memory, there is no reason to pick any particular deallocation order.

like image 100
Nicol Bolas Avatar answered Sep 05 '25 06:09

Nicol Bolas