Reputation: 450
I'm getting a runtime 217 error that I've tracked down to the finalization section of one of my units. This is the code :
finalization
begin
for I:= 0 to CacheList.Count - 1 do
begin
tempRecord := CacheList.Items[I];
for k := 0 to length(tempRecord.details) - 1 do
begin
tempRecord.Details[k].free;
end;
tempRecord.free;
end;
CacheList.Free;
end;
and tempRecord is :
Record = class
Details : array of CachedDetails;
key : string;
end;
CachedDetails = class
EDate : TDateTime;
A : Real;
B : Real;
C : Real;
end;
Even though I get the error, the process does completely successfully. And if I simply comment out the entire finalization the error goes away, but I obviously don't want to leak memory. Am I improperly calling the frees?
Upvotes: 1
Views: 423
Reputation: 19096
It is not a good advice to Free Items of a List, while they belong to the list. You have to check if it is a kind of TObjectList and if this List owns the objects.
Or you Extract the Item from List and free it.
finalization
begin
while CacheList.Count > 0 do
begin
tempRecord := CacheList.Extract( CacheList.First );
for k := 0 to length(tempRecord.details) - 1 do
begin
tempRecord.Details[k].free;
end;
tempRecord.free;
end;
CacheList.Free;
end;
But just as a think it over, if you hand over the destroy responsibility to the Record class and CacheList a TObjectList with OwnsObjects=True then your finlization code will look like this
finalization
CacheList.Free;
Upvotes: 1