MemCheck tutorial: find bad interface calls
- Create a new class which implements IUnknown (warning: this is for the lesson only -
this code is not good for real use)
TMyUnknown = class(TObject, IUnknown)
protected
fCount: Cardinal;
public
function
QueryInterface(const IID: TGUID; out
Obj): HResult; stdcall;
function
_AddRef: Integer; stdcall;
function
_Release: Integer; stdcall;
end;
function TMyUnknown._AddRef: Integer;
begin
fCount:= fCount + 1;
end;
function TMyUnknown._Release: Integer;
begin
fCount:= fCount - 1;
if
fCount = 0 then
Destroy;
end;
function TMyUnknown.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
end;
- Write the BadInterf procedure
procedure BadInterf;
var
i: IUnknown;
o: TMyUnknown;
begin
o:= TMyUnknown.Create;
i:= o;
o.destroy;
end;
- From the dpr's body call BadInterf
begin
MemChk;
BadInterf;
end.
- MemCheck tells you that you are calling a method of an interface while the underlying
object has been destroyed (the compiler has generated a call to ReleaseRef on exit of
BadInterf). Of course, this feature of MemCheck is less often useful than others; but when it is, you'll thank MemCheck !
Last update: March 2001