Memory Leak in TDictionary - Problems with a Workaround?

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 freeing up the two objects that cause the leak:

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

The problem is that the values ​​and keys are read-only properties of the TDictionary, I cannot set them to nil. Well, just to be clear, everything works fine now, but I wondered what would happen if CodeGear releases a patch for a leak and frees two objects again in its own destructor. Wouldn't that lead to an access violation?

Thanks in advance for reading (and hopefully an answer).

+3
source share
3 answers

First you can call inheritedand check if all the properties are set:

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

And by the way: Freedoesn't care if the freed instance will be nil, so it will work if (but only if) inherited Destroysets the properties to nil.

+2
source

I do not know how in previous versions of Delphi, but in XE5 there is a class TObjectDictionary, which takes care of freeing all subelements.

+1
source

, .

TObjectDictionary<string, TMyClass>.Create([doOwnsValues]);
0

Source: https://habr.com/ru/post/1702691/


All Articles