Appendix B. The Prevention of Memory Leakage
One of the most dangerous pitfalls affecting the C++ community is that of memory leakage, or the unintentional nondeletion of dynamically allocated memory. A system inflicted with this problem will run correctly for some period of time, often weeks, with no discernable problem. It will then "seize up," that is, run out of heap space for no apparent reason. The operator typically reboots the application, which again runs problem-free. The danger of this situation is that it is not caught at compile, link, or test-run time. It is detected only after the product has been shipped to a number of clients.
While memory leakage has occurred in standard C applications, it is typically introduced into that environment when a developer dynamically allocates space and simply forgets to free it. The problem is accentuated in C++ because most memory leakage occurs through the compiler's implicit function calls, making detection dependent on the developer knowing the inner workings of C++. In the course of much C++ development, I have identified eight programming areas prone to C++ memory leakage. These range from the mundane and obvious, such as forgetting to delete space that was explicitly allocated, to the more esoteric reasons, such as confusing arrays of pointers with arrays of objects, forgetting to make a base class destructor virtual, missing copy constructors, missing overloaded assignment operators, missing size arguments to the delete function, and using a poor design when constructing overloaded operators. The following text details each of these problem areas and provides a C++ coded example for each. Developers armed with these examples will be able to relegate memory leakage to the class of pitfalls that are infrequently encountered and easily overcome.