Consider this short Delphi procedure:
procedure TfrmXQuery.FieldListFillFromDefault;
var
field_list: TStringList;
begin
try
if x <> '' then begin
field_list := TStringList.Create;
{do some stuff with field_list}
end;
finally
if field_list <> NIL then
begin
field_list.Free;
end;
end;
end;
When I run this in, Delphi 3, with x = '' so that field_list is never created,
- why is
field_list <> NIL
? - are objects not initialized as
NIL
? - if it's not
NIL
what is it? - and if it's unassigned and not
NIL
how do I know whether or not toFree
it? TheAssigned
function does not tell me:if Assigned(an_object)
is equivalent toif an_object = NIL
Answers to the questions:
why is
field_list <> NIL
? Delphi does not initialize local objects. For more details see: Why doesn't object default to nil? and Are delphi variables initialized with a value by default?are objects not initialized as
NIL
? Global objects: Yes. Local objects: No.if it's not
NIL
what is it? Invalid pointers.and if it's unassigned and not
NIL
how do I know whether or not toFree
it? You need to reorganize your code (see below). TheAssigned
function does not tell me:if Assigned(an_object)
is equivalent toif an_object = NIL
. Assigned tests for a nil (unassigned) pointer or procedural variable. <--from Delphi 3 documentation. Uninitialized local objects are not assigned NIL soAssigned(an_object)
returns TRUE if an_object is local and has never been used (assigning NIL is using the object).Because objects local to a procedure are not initialized to NIL, I have revised the code from the question assigning all local objects that are local to NIL. I do these assignments at the very beginning of the routine so that Free will not error out if the local objects are never created. I've also shown the error tracking code that was left out of the original question:
The entire routine is protected by
try...except
. Iffield_list
orsome_other_object
are created it will be freed. They are assigned NIL at the very beginning so freeing them in the 'try...finally` block will not raise an error even if there is a run time error before they are created.