1. Computing & Technology

Discuss in my forum

A warning on dynamically instantiating components

By , About.com Guide

10 of 10

Risk of a Double Free

This code also introduces the risk of Delphi attempting to free the dynamically-created instance twice (this is a bad thing, and can result in AVs and other problems). This will happen if the owner is freed within the Try/Finally block.

This could happen unexpectedly if the code inside the Try block was time-intensive, and a method within the block directly or indirectly called Application.ProcessMessages. If this condition existed, and the user closed the form while execution was in the Try block, then the form would be destroyed in the call to Application.ProcessMessages. When the form is destroyed, it also destroys all owned components (including the TTable). At this point in the execution, the reference created by "TTable.Create" is invalid. Any further references to that TTable object (e.g., calling methods or setting properties of TTable) would most likely result in access violations, as would the final call to Free. If this were to occur, it would be a problem that would be extremely difficult to find, debug, and ultimately trace back to the fact that you should have passed nil in as the owner to the dynamically created and locally-used TTable.

Summary

If you want to dynamically create a component and explicitly free it sometime later, always pass nil as the owner. Failure to do so can introduce unnecessary risk, as well as performance and code maintenance problems.

©2012 About.com. All rights reserved.

A part of The New York Times Company.