Memory management and leak detection
Since C++ does not have garbage collection, one is required to release every piece of dynamically allocated memory as soon as one is finished with it. When using the JX Application Framework, widgets and directors are effectively garbage collected because they are deleted by their enclosures and owners, respectively, and JPtrArray provides the option to delete all the objects when the array is destroyed, but everything else must still be released by hand. When one forgets to do this, one has a memory leak.
JMemoryManager was created to track down memory leaks. When you #include <jNew.h> (which is done automatically by jAssert.h), it automagically overrides operator new and operator delete to keep track of all memory allocation and deallocation. To find memory leaks, set the environment variables JMM_RECORD_ALLOCATED and JMM_PRINT_EXIT_STATS to yes, start the program, exercise all its features, and then quit. Each block of memory that was not deallocated will be reported, along with the source file name and line number where it was allocated. With this information, all you have to do is figure out where each block of memory ought to be deallocated.
JMemoryManager also provides several other useful features:
- If you set the environment variable JMM_INITIALIZE to a numerical value, that value will be used to fill memory when it is allocated. This helps you catch code that accesses memory without first initializing it.
- If you set the environment variable JMM_SHRED to a numerical value, that value will be used to erase memory when it is deallocated. This helps you catch code that accesses memory after deallocating it. (Some systems will not generate a segmentation fault in some cases.)
A more thorough explanation of these and other, more arcane features is provided in the source file JMemoryManager.cc.