There are cases when the basic resource allocation pattern is not applicable. This usually happens in programs which use dynamic data structures. When there are top level structures and inner level structures, some resources are allocated to the top level and some are allocated to inner levels. If there are multiple levels of structures, the resource allocation is done for each level separately.
What happens when we deallocate the top level structure? We have three main options:
- The top level structure is also responsible for deallocating the substructures. There substructures again recursively deallocates its substructures.
- The top level structure is simply deallocated, thereby making all its substructures orphans
- The top level structure refuses to deallocate if it contains any substructures.
The choice depends on each individual data structures and their circumstances. In languages like C, where data structures themselves are not active, we can write a module for each major structure that take care of standard allocation and deallocation.
Checking the Balance
It is always a good idea to build code that checks if the resources are freed properly. For most of the applications this means producing wrappers for each resources that keep track of allocations and deallocations.
At a lower, but no less useful level, you can invest in tools that check your running programs for memory leaks.
- summary of When You Can't Balance Resources, from The Pragmatic Programmer: from Journeyman to Master
No comments:
Post a Comment