4

My application spawns several independent forms. Once when created the application forgets about them. All action is handled in that form itself. When the application closes the form closes also, by the RTS i suppose. This is fine except that neither the OnClose nor the OnDestroy event are being fired, so memory leaks occur. I can administer which forms are present (as i do now) but actually the application must completely forget about these forms.

Is there a way to detect inside a form, being not the application main form, that the application is in the process of being closed?

Arnold
  • 4,016
  • 5
  • 42
  • 82
  • Even if the dtor for the form is not called, (eg. the code calls 'halt' or ExitProcess()), there should be no memory leaks if the app terminates - the OS will eat up the forms if nothing else does. That apart, you have to try quite hard to not get Destroy called - the application keeps a list of forms and destroys them all on app close. – Martin James Jan 25 '12 at 13:18
  • @Martin, you needn't try hard, just forgetful. I created the form with `nil` as argument of `Create`. David's answer reminded me that this was not such a good idea :-) – Arnold Jan 25 '12 at 18:39

1 Answers1

6

The OnDestroy event certainly will fire if the form is destroyed. It's invoked from the form's destruction code. So the only conclusion is that your form is not being destroyed and so is leaked.

There are a couple of obvious ways to make sure that your independent forms are not leaked:

  1. When you create then, pass either Application or MainForm as the owner parameter of the form. When the owner is destroyed, it will also destroy everything it owns, including your forms.
  2. Explicitly destroy these forms from, for example, the main form destructor or the .dpr file after the call to Application.Run returns.

Option 1 is the most commonly used approach.

David Heffernan
  • 572,264
  • 40
  • 974
  • 1,389