I'm writing a shell in C. While I don't expect many other people to use it, I'd like to practice writing maintainable and well-organized code. I've noticed the following pattern in a number of my functions, so before it solidifies, I'd like it to be fully vetted.
As an example, consider the following function:
int foo(int param...) {
// declare variables
struct bar *a, *b, *c;
// do some work
a = bar_creator();
b = bar_modifier(a);
c = bar_modifier(b);
// cleanup
free(a);
free(b);
free(c);
return 1;
}
Things to note:
three phases: declaration, initiation/modification, cleanup
newly allocated structures are often returned from functions as modified copies of other objects
a huge number of objects are not needed, so memory usage is not an issue
As it stands, the three sections have been relatively distinct. This allows me to match up the first and last sections and ensure everything is accounted for. Now I wonder if a better style might be to deallocate something as soon as it is not needed. A motivation for this might be to minimize the context within which a code section makes sense.
What is your approach to deallocation of resources? What are the advantages of the given strategy?
edit
To clear up any confusion as to the behavior of functions:
/**
* returns a newly created bar
*/
struct bar *bar_creator();
/**
* takes a bar, and returns a _new_ copy of it that may have been modified.
* the original is not modified.
*/
struct bar *bar_modifier(struct bar *param);