[fpc-pascal] Where and Why is there a memory leak?
Graeme Geldenhuys
mailinglists at geldenhuys.co.uk
Wed Sep 6 11:55:14 CEST 2017
On 2017-09-06 10:41, Sven Barth via fpc-pascal wrote:
> I think THook needs to derive from TAggregatedObject, cause that couples
> the reference counting to that of the controlling instance.
That seems to be heading in the right direction, but such a change on
its own doesn't seem to solve the two memory leaks either. I'll test
under Delphi XE which can report memory leaks to see what it does with
that same code. So this might end up being a bug in FPC somewhere.
Either way, modifying the example to use a getter method AND
TAggregatedObject, I managed to get rid of both memory leaks. Here is
the working [memory leak free] code now:
=======================[ 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;
function GetHook: IHook;
property Hook: IHook read GetHook implements IHook;
public
destructor Destroy; override;
end;
function TBaseClass.GetHook: IHook;
begin
if FHookInstance = nil then
FHookInstance := THook.Create(self);
Result := FHookInstance;
end;
destructor TBaseClass.Destroy;
begin
FHookInstance.Free;
inherited Destroy;
end;
var
base: IHook;
begin
base := TBaseClass.Create;
base.DoIt;
base := nil; // just to see if it helped with the memory leak - it
doesn't
end.
========================[ end ]===============================
And the program output:
[t1]$ ./project1
THook did it
Heap dump by heaptrc unit
4 memory blocks allocated : 107/112
4 memory blocks freed : 107/112
0 unfreed memory blocks : 0
True heap size : 1114112 (32 used in System startup)
True free heap : 1114080
I can't remember ever [while using Delphi] being forced to implement a
getter method in the "property ... implements..." line, but it seems
that is the only way it remove memory leaks under FPC. Weird. :-/
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