Forum > LCL

Some things are not Free(d)

(1/1)

iru:
Gentlefolk,

Lazarus 0.9.28, ZEOS 6.6.6, Ein XP SP3.

I have the following code:


--- Code: ---  if FormOmega.FO = NIL then
    FormOmega.FO := TFormOmeg.Create(Self);
  FormOmega.FO.ShowModal;
  FormOmega.FO.Free;         

--- End code ---

Code executes OK, form is created, form is displayed.

On return from the ShowModal the .Free is executed but does not appear to release the FormOmega.FO.

Next time through FormOmega.Fo is not NIL, the create is skipped and the program crashes on the ShowModal.

FO.FormCreate includes "inherited".

From experience, examples, Delphi documentation, etc the above code looks OK.

Any ideas, comments, suggestions......

Ian

theo:
Not sure if this is the reason, but I'd do it like this example:


--- Code: --- if Form2=Nil then
    Form2:=TForm2.Create(nil);
  Form2.ShowModal;
  FreeAndNil(Form2);       
--- End code ---

See Create(Nil) and FreeAndNil.

Martin_fr:

--- Quote from: iru on April 30, 2010, 10:18:49 am ---Gentlefolk,

Lazarus 0.9.28, ZEOS 6.6.6, Ein XP SP3.

I have the following code:


--- Code: ---  if FormOmega.FO = NIL then
    FormOmega.FO := TFormOmeg.Create(Self);
  FormOmega.FO.ShowModal;
  FormOmega.FO.Free;        

--- End code ---

On return from the ShowModal the .Free is executed but does not appear to release the FormOmega.FO.

Next time through FormOmega.Fo is not NIL, the create is skipped and the program crashes on the ShowModal.

From experience, examples, Delphi documentation, etc the above code looks OK.

--- End quote ---

The code is correct. (except for not setting  FormOmega.FO to nil)

What you need to know, is that FormOmega.FO in reality is a pointer.

Pascal hides this fact from you on almost every level. But in some cases you still get to see the behaviour of a pointer.

That means looking at your TFormOmeg object, you have:
1) the object, somewhere in memory (allocation/deallocation is handled automatically)
2) FormOmega.FO a pointer to this memory
3) any other amount of pointers
  SomeOtherFO := FormOmega.FO;

the object doesn't know how many pointers point to it, nor where the pointers are.

  FormOmega.FO.Free;
frees the object, and deallocates the memory used by it. (but because the object doesn't know the pointer(s), the pointer(s) are still pointing to this (no unused or re-used for something else) memory)

So yes, next time FormOmega.FO still points to somewhere. but the location it points to does not have any usable content.


FreeAndNil(FormOmega.FO); goes one step further. It calls:
  FormOmega.FO.Free;
and does
  FormOmega.FO := nil;

Note: If you have more pointers to this objects, all other pointers still point to the now invalid memory.

iru:
Gentlefolk,

Thank you for the responses (and solutions).

Ian.

Navigation

[0] Message Index

Go to full version