R – Memory Leak in TDictionary – Problems with Workaround

delphidelphi-2009memory-leaks

I just considered using the new TDictionary type. But On QualityCentral I read about two memory leaks caused by TDictionary:

http://qc.codegear.com/wc/qcmain.aspx?d=67355

I just implemented the proposed workaround, basically subclassing TDictionary, overriding the destructor and manually freing the two objects that cause the leak:

destructor TMemCorrectedDictionary.Destroy;
begin
  Values.Free;
  Keys.Free;
  inherited;
end;

Problem is, since Values and Keys are read-only properties of TDictionary, I can't set them to nil. Well, just to be clear, everythings works fine now, but I wondered what would happen if CodeGear releases a patch for the leak and frees the two objects again in their own destructor. Wouldn't this cause an access violation?

Thanks in advance for reading (and hopefully answering).

Best Answer

You could call inherited first and check if the properties are still set:

destructor TMemCorrectedDictionary.Destroy;
begin
  inherited;
  Values.Free;
  Keys.Free;
end;

And by the way: Free doesn't care if the instance to be freed is nil, so this will work if (but only if) inherited Destroy sets the properties to nil.