jpfollenius
jpfollenius

Reputation: 16612

Memory Leak in TDictionary - Problems with 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 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).

Upvotes: 3

Views: 2913

Answers (3)

hikari
hikari

Reputation: 3503

Use this parameter when creating the dictionary and it will free the objects.

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

Upvotes: 0

XWiśniowiecki
XWiśniowiecki

Reputation: 1843

I don't know how about previous versions of Delphi but in XE5 there is TObjectDictionary class that take care of freeing all the subitems.

Upvotes: 2

Heinrich Ulbricht
Heinrich Ulbricht

Reputation: 10372

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.

Upvotes: 2

Related Questions