The Pragmatic Programmer: From Journeyman to Master
Checking the Balance
Because Pragmatic Programmers trust no one, including ourselves , we feel that it is always a good idea to build code that actually checks that resources are indeed freed appropriately. For most applications, this normally means producing wrappers for each type of resource, and using these wrappers to keep track of all allocations and deallocations. At certain points in your code, the program logic will dictate that the resources will be in a certain state: use the wrappers to check this.
For example, a long-running program that services requests will probably have a single point at the top of its main processing loop where it waits for the next request to arrive . This is a good place to ensure that resource usage has not increased since the last execution of the loop.
At a lower, but no less useful level, you can invest in tools that (among other things) check your running programs for memory leaks. Purify (http://www.rational.com) and Insure++ (http://www.parasoft.com) are popular choices.
Related sections include:
-
Design by Contract
-
Assertive Programming
-
Decoupling and the Law of Demeter
Challenges
-
Although there are no guaranteed ways of ensuring that you always free resources, certain design techniques, when applied consistently, will help. In the text we discussed how establishing a semantic invariant for major data structures could direct memory deallocation decisions. Consider how Design by Contract, could help refine this idea.