Monday, February 1, 2010

Delphi: Preventing Memory Leaks During Dynamic Object Creation

Memory handling can be a nightmare in Delphi when creating and destroying objects dynamically.

Normally,you can just drag-drop components on to the form and Delphi takes care of allocation and deallocation of memory. However,there are times when dynamic objects are the only answer to specific problems. Besides,even in standard applications, dynamically created objects can help optimize memory usage. For instance,all objects drag-dropped on forms are treated as global i.e. they are created when the application initializes and are destroyed when it terminates. Many of these objects may not be used throughout the life-time of the application but in a block only, yet declaring them globally locks up resources unnecessarily. Creating objects at runtime and on-demand can among other things enhance the performance.

But on the flip side, not properly freeing up objects can lead to hard-to-find memory leaks. To avoid them,you can use the try.. finally.. block, create the object in the 'try' section and explicitly release more in the finally block.

For more read on..
http://www.devarticles.com/c/a/Delphi-Kylix/Using-Try-and-Finally-to-Help-Prevent-Memory-Leaks-During-Dynamic-Object-Creation-in-Delphi/