How to free all memory allocated by an object - Delphi

10

What is the best way to release all memory allocated by creating an object to the S.O.

Let's not consider:

Objeto.Free;
Objeto := Nil;
Sysutils.FreeAndNil(Objeto);

Would there be more ways to free up memory for OS?

    
asked by anonymous 18.02.2014 / 13:35

3 answers

6

Taking advantage of the Math response, if you simply set nil to the object it is still allocated, but you are disassociating the variable pointer from the memory area occupied by the object.

When you call the method

Objeto.Free

You are releasing this object from memory

The difference between the .Free and FreeAndNil methods is that the free and nil after release object returns the nil value for the variable.

Using FreeAndNil is more common to avoid errors where you after releasing an object want to validate if the object has information:

Objeto := TObject.Create;
Objeto.Free;
if Assigned(Objeto) then
  ShowMessage('Vai entrar aqui.');

Otherwise:

Objeto := TObject.Create;
FreeAndNil(Objeto);
if Assigned(Objeto) then
  ShowMessage('NÃO vai entrar aqui.');

So, the answer to your question, both .Free and FreeAndNil release the whole object and issue between using Free and FreeAndNil is based more on best practices.

    
18.02.2014 / 16:13
1

You can use the following function that frees the memory and zeros the object, which would be the following function:

procedure FreeMemAndNil(var ptr; size: Integer = -1);
var
  p: Pointer;
begin
  p := Pointer(ptr);
  if p <> nil then
  begin
    if size > -1 then
      FreeMem(p, size)
    else
      FreeMem(p);
    Pointer(ptr) := nil;
  end;
end;

Or simply use the function FreeMem(pointer,size);

Reference

    
18.02.2014 / 13:46
1

The language documentation explains that the correct way to free memory occupied by a class instance is to invoke destructor of this class.

However, for good practice reasons, you should always use the Free or FreeAndNil methods (as explained in other answers) and not invoke the Destroy method directly, even if this is in fact possible.

After the code for destructor is executed, the FreeInstance method is invoked for the Delphi memory manager to return this block of memory that was occupied by the instance.

However, does not mean that memory will be returned to the operating system , it will generally be available in a chained list of blocks of free memory to be reused without being necessary to allocate system memory again (expensive process).

The memory block is only actually released to the operating system when it corresponds to a heap end memory block (dynamic allocation memory area). In this case the memory manager will shrink heap , releasing all contiguous blocks from the end to the beginning.

The process is this because it is not possible to free memory blocks from the middle of heap , leaving gaps in it. The heap needs to be contiguous.

    
08.05.2014 / 20:50