1. Home
  2. Computing & Technology
  3. Delphi Programming

A warning on dynamically instantiating components

By Zarko Gajic, About.com

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.
Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Using VCL Components
  5. Run time VCL creation
  6. A warning on dynamically instantiating Delphi components

©2009 About.com, a part of The New York Times Company.

All rights reserved.