#430 Free members of fPlugins and others

closed-invalid
Core (49)
5
2012-02-23
2012-01-27
No

This little piece of code in TCustomSynEdit.Destroy only frees the parent TList but leaves the objects pointed to in the same TList in memory, producing a memory leak:

fHookedCommandHandlers.Free;
fHookedCommandHandlers := nil;

fPlugins.Free;
fPlugins := nil;

I suggest modifying this to (for example):

if Assigned(fHookedCommandHandlers) then
for I := 0 to fHookedCommandHandlers.Count - 1 do
TObject(fHookedCommandHandlers[i]).Free;
fHookedCommandHandlers.Free;

if Assigned(fPlugins) then
for I := 0 to fPlugins.Count - 1 do
TObject(fPlugins[i]).Free;
fPlugins.Free;

... which does free the objects pointed to, provided these objects have got a proper destructor of course.

Discussion

  • Eric Grange

    Eric Grange - 2012-02-23
    • assigned_to: nobody --> egrange
    • status: open --> open-invalid
     
  • Eric Grange

    Eric Grange - 2012-02-23

    fHookedCommandHandlers and fPlugins are actually TObjectList, not TList, and TObjectList releases its objects automatically.

     
  • Eric Grange

    Eric Grange - 2012-02-23
    • status: open-invalid --> closed-invalid
     
  • orwelldevcpp

    orwelldevcpp - 2012-02-23

    It must be my version of the VCL messing stuff up then, but at least in Delphi 7, you need to set OwnsObjects to true, which you can do by passing true to the creator. Otherwise, TObjectList behaves like TList when it comes to this stuff.

    One other thing, why not use TList?

     
  • Eric Grange

    Eric Grange - 2012-02-23

    The default TObjectList.Create constructor (without parameters) sets OwnsObject to true. You only need to call the parameterized constructor when you don't want TObjectList to own the objects.

    That's the case in Delphi 7 too (cf. Contnrs.pas)

    >One other thing, why not use TList?

    TList contains pointers, TObjectList contains TObject, (yes, one does use the other as container), and using TObjectList avoids having to duplicate the cleanup loop everywhere you have lists of owned objects.

     

Log in to post a comment.