A dangling reference
The second kind of error is to free the object without then setting the name to nil. The name then refers to an object that no longer exists. This is sometimes called a dangling reference. It is particularly likely to occur where we have several references to the same object and do not nil them all when freeing the object.Freeing objects, components and forms
Delphi has two methods for deallocating objects, Free and Destroy. When working with programmer generated objects, we use Free with very few exceptions.This is because Free firsts checks that an object does actually exist. If it does, Free calls Destroy to deallocate the object. If not, it exits without attempting to deallocate a non-existent object. But what happens with RAD objects (ie Components)? When a Component is freed, it frees all the Components it owns before it allows itself to be destroyed.
The Application owns all the forms and so when the program ends the Application frees all of the forms. Each form in turn frees the Components on it. As a consequence, when the programmer instantiates a component in program code, the create constructor must be passed a parameter to identify the owner (as in example 1.3 step 7: see that discussion). Any object that the programmer has created and that still exists when the Application terminates is deallocated automatically.
However, if objects are not needed for the duration of the Application they should be freed when no longer needed to avoid clogging memory unnecessarily. This applies particularly to programs with large numbers of transient objects and for long-running programs. However, be careful not to free an object or Component in one of its own methods or event handlers!
A form can be freed explicitly by calling its Release method. This waits until all the event handlers of the form and its Components have finished before deallocating the form.
That's it for this chapter, next time we'll discuss properties and methods in custom defined classes...

