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?
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);
To deallocate previously allocated memory, we will use the standard library function realloc(). The "realloc()" function declaration from "stdlib.
Only deallocate memory when you are truly finished with that memory. If you have more than one pointer to a chunk of memory, then deallocating that chunk makes all pointers to it stale; they are pointing to memory that you are no longer allowed to use. Those pointers are called dangling pointers.
In C, the library function malloc is used to allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. When the memory is no longer needed, the pointer is passed to free which deallocates the memory so that it can be used for other purposes.
Mainly free() function is used for allocating free memory for malloc() and calloc(). The free(var-name) is only function in c to deallocate memory.
Personally, my preference is to free objects directly after I'm done using them, and only allocate directly before I need them. This forces me to understand what memory my program is actually using. Another benefit of this technique is that it reduces total memory consumption if you allocate additional memory after you free memory in the method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With