Search code examples
delphimemory-leaksanonymous-methods

Memory leaks happens in nested anonymous method


In Delphi XE, the following code will cause memory leak:

procedure TForm1.Button1Click(Sender: TObject);
var P, B: TProc;
begin
  B := procedure
       begin
       end;

  P := procedure
       begin
         B;
       end;
end;

Run the code with

ReportMemoryLeaksOnShutdown := True;

and the memory manager prompt:

21-28 bytes: TForm1.Button1Click$ActRec x 1

Solution

  • This is a bug in the compiler (as far as I know). I opened QC83259 in Embarcadero's quality central about it.

    You can work around this bug by creating the anonymous procedure in a routine. The following code won't leak.

    procedure TForm1.Button1Click(Sender: TObject);
    var P, B: TProc;
    begin
      B := GetMethod(); //Note, the "()" are necessary in this situation.
      P := procedure
      begin
        B;
      end;
    end;
    
    
    function TForm1.GetMethod: TProc;
    begin
      Result := procedure
      begin
      end;
    end;