views:

276

answers:

1

Hi everybody,

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).

+2  A: 

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.

Heinrich Ulbricht
This is dangerous, as the inherited will have free'd the memory that you reference afterwards. Just .Free is fine as it automatically checks for nil.
mj2008
I don't understand. The above code is only dangerous if CodeGear provides a fix which frees the variables Values and Keys and does NOT set them to nil afterwards. But it is the best you can do. It is definitely better than freeing them without setting them to nil and calling inherited afterwards.
Heinrich Ulbricht