Monday, January 21, 2008

Delphi Memory Leak

I have a lession learn today when I work with delphi. We should avoid using Tlist to store object which implemented any interfaces.

We should use TinterfaceList instead of Tlist. The reason is: Tlist use pointer to reference to object. When we get an object and from that object we get one of its interfaces. This interface is not referenced by anyone (although Tlist use pointer to point to the object) .Therefor when go out of variable scope, this interface is freed automatically.

Hereunder is the sample explaining the lession.


InterfaceA = Iinterface
Procedure methodA;
End;


ClassA = class(TinterfaceObject, InterfaceA)
Procedure methodA;
End;


Var
A: TOBbject
List: Tlist;
Begin
List := Tlist.Create;
List.Add(A);
methodX;
methodY; ==> Exception occur here.
End.

Procedure methodX;
Var
X: InterfaceA;
Obj: ClassA;
Begin
Obj := Tlist.Items[0];
Obj.QueryInterface(InterfaceA, X); ==> Get interface here. Reference count increased to 1
End; ==> Interface will release reference count. Reference count = 0 ==> Obj is freed.

Procedure methodY;
Begin
Obj := Tlist.Items[0];
Obj.methodA; รง Exception because of object is freed.
End;


Hope this lession lean can help you avoid unexpected exception.

No comments:

Google