[fpc-pascal] Where and Why is there a memory leak?

Graeme Geldenhuys mailinglists at geldenhuys.co.uk
Wed Sep 6 15:01:49 CEST 2017


On 2017-09-06 11:33, Marcos Douglas B. Santos wrote:
> You have resolved just by change FHookInstance
> as a class, not an Interface, plus using TAggregatedObject too.

Ah yes, that seems to work too. Many thanks for pointing that out.

So here is another implementation that works with NO memory leaks.

========================[ project1.pas ]============================
program project1;

{$mode objfpc}{$H+}
{$interfaces COM}

type
   IHook = interface
     ['{4BCAEDD8-92D8-11E7-88D3-C86000E37EB0}']
     procedure DoIt;
   end;

type
   THook = class(TAggregatedObject, IHook)
   private
     procedure DoIt;
   end;

   procedure THook.DoIt;
   begin
     writeln(ClassName + ' did it');
   end;

type
   TBaseClass = class(TInterfacedObject, IHook)
   private
     FHookInstance: THook;
     property Hook: THook read FHookInstance implements IHook;
   public
     constructor Create;
     destructor Destroy; override;
   end;

   constructor TBaseClass.Create;
   begin
     inherited Create;
     FHookInstance := THook.Create(self);
   end;

   destructor TBaseClass.Destroy;
   begin
     FHookInstance.Free;
     inherited Destroy;
   end;


var
   base: IHook;

begin
   base := TBaseClass.Create;
   base.DoIt;

end.
==============================[ end ]===============================


Yeah, just as I said.... Interfaces are an advanced feature of the 
Object Pascal language. Lots of traps!

Bottom line:

     NEVER code without enabling memory leak detection!!!  :)


Regards,
   Graeme

-- 
fpGUI Toolkit - a cross-platform GUI toolkit using Free Pascal
http://fpgui.sourceforge.net/

My public PGP key:  http://tinyurl.com/graeme-pgp



More information about the fpc-pascal mailing list