Search code examples
delphifreefreezefpc

Hang on SomeObject.Free. Check if object is already free in FPC?


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();?


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.