Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when I free memory that may not exist in Delphi?

Delphi doesn't have a garbage collector, so coming from a Java background this is a real pain in the neck.

Usually, to destroy some memory I won't use anymore I'd use:

if (SomeMemory <> nil) then
  SomeMemory.Free

What would happen if I don't check for nil before deleting?

Additionally, why someone would want to deal with all this "garbage collecting" by himself? Why among all the compiling options Delphi has, there is no Garbage Collector = true

like image 874
Diego Rueda Avatar asked Nov 30 '22 19:11

Diego Rueda


1 Answers

The code for TObject.Free looks like this :

procedure TObject.Free;
begin
  if Self <> nil then
    Destroy;
end;

So there is no need to check for nil. You can still get into trouble if you try to free an uninitialized variable, however, as this will result in an AV. Checking for nil (or Assigned) obviously doesn't help you there either. The compiler will warn you if you try to do this, however.

To answer your second question

Why among all the compiling options Delphi has, there is no Garbage Collector = true

The simple answer is that Delphi does not have such a garbage collector. Certain managed types (like strings, dynamic arrays, etc) implement compiler-managed automatic reference counting, and those objects are automatically freed when their reference counts fall to zero. For all other unmanaged objects it is the responsibility of the developer to appropriately clean up object instances when they are no longer needed.

It's not a question of wanting to have to manage your application's memory, it's just a matter of course that you need to.

like image 69
J... Avatar answered Dec 24 '22 02:12

J...