Search code examples
classdelphimemory-leakstdictionary

Delphi - Confused about memory allocation in TDictionary


In Delphi XE6, I have a TDictionary called WordDict which holds instances of TWordRec. Definitions are:

 WordDict: TDictionary<string, TWordRec>;

...

type
  TWordRec = class
  public
    RemoveAlways: Boolean; // Is this CORP LLC, etc?
    RemoveRestricted: Boolean;
    Replace: Boolean;
    ReplaceWith: string;
    Constructor Create(B1, B2, B3: Boolean; S1: String); overload;
  end;

When I create and load the Dictionary....

  WordDict := TDictionary<string, TWordRec>.Create;

  WordDict.Add('CO', TWordRec.Create(True, False, False, ''));
  WordDict.Add('CORP', TWordRec.Create(True, False, False, ''));
...

I am running into a memory leak, and using AQTime, its showing each occurrence of my TWordRec is "leaking" memory. If I am creating the WordDict entries as TWordRec, how do I dispose of them after they are loaded? Do I dispose of them, since isn't this just a pointer in the dictionary to the actual object?

Do I dispose of the TWord immediately after loading? Do I delete all the entries from my Dictionary ONLY when the app closes down? I obviously don't understand WHY I am getting a memory leak on TWordRec, so I don't know how to resolve it...

Thanks!


Solution

  • You aren't getting a memory leak on TWordRec, rather the TDictionary isn't behaving as you'd expect. The standard TDictionary class doesn't have any mechanism for object ownership. If you change your container class to TObjectDictionary and create it with the doOwnsValues option set, it will automatically free the owned objects on destruction which is the behaviour you are expecting.

    The alternative is to iterate through the items freeing each object in your TDictionary instance before finally freeing the TDictionary object.