Question

if if have an object (in my case TJSONData) and I want to free this object the programm flow sometimes hangs at this position. I already have a construct like the following in my code but it seems to not fit the case some times:

if Assigned(MyRecord.MyJSONData) then
begin
  MyRecord.MyJSONData.Free;
end;

I can reproduce this behavior in tests if I try to free an object two times. In my program this should normally not happen but now my real question:

Is there a way to check if the object is already free? Or do I need to use also FreeAndNil();?

Was it helpful?

Solution

The Assigned function checks to see if a reference is not nil. It returns True if not nil, and False if nil.

Obviously when you free the object and do not set reference to nil it will pass on next Assigned check (reference <> nil) and will be attempted to free again. But the reference (pointer) is already dangling (pointing to freed or worse, changed, memory).

Generally you should set your references to nil or better - use FreeAndNil function. This way each time you will want to access the freed object it will be nil and thats your check.

OTHER TIPS

There was a large thread in Delphi forum (the tread that eventually crushed the forum) about FreeAndNil.

Common point was that for 95% of tasks you should not check if an object is alive, you should know it beforehand and architect the program so that you always know and never need those checks.

Some survived or revived links are at http://www.theregister.co.uk/2012/01/16/verity_stob_sons_of_khan_2011/print.html and at https://forums.embarcadero.com/message.jspa?messageID=413796

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top