[fpc-pascal] Where and Why is there a memory leak?
Michael Van Canneyt
michael at freepascal.org
Wed Sep 6 10:37:46 CEST 2017
On Wed, 6 Sep 2017, Graeme Geldenhuys wrote:
> Hi,
>
> Playing with this small sample application to answer another question in
> this mailing list, I noticed the sample application has a memory leak.
> For the life of me I can't see why or how to resolve it.
>
> I tested with FPC 2.6.4, 3.0.2 and 3.0.4-rc1 under 64-bit FreeBSD.
>
> =======================[ project1.pas ]============================
> program project1;
>
> {$mode objfpc}{$H+}
> {$interfaces COM}
>
> type
> IHook = interface
> ['{4BCAEDD8-92D8-11E7-88D3-C86000E37EB0}']
> procedure DoIt;
> end;
>
> type
> THook = class(TInterfacedObject, IHook)
> private
> procedure DoIt;
> end;
>
> procedure THook.DoIt;
> begin
> writeln(ClassName + ' did it');
> end;
>
> type
> TBaseClass = class(TInterfacedObject, IHook)
> private
> FHook: IHook;
> property Hook: IHook read FHook implements IHook;
> public
> constructor Create;
> destructor Destroy; override;
> end;
>
> constructor TBaseClass.Create;
> begin
> FHook := THook.Create; // FPC 2.6.4 reports a memory leak here
> end;
>
> destructor TBaseClass.Destroy;
> begin
> // nothing to do here
> end;
You must free FHook here, because you are keeping a reference to the object,
not the interface. And you must call inherited.
You must always call inherited in the destructor.
Michael.
More information about the fpc-pascal
mailing list