[fpc-pascal]Memory leak in freepascal, FreeAndNil not working properly?
Andreas Gros
andreas.gros at biozentrum.uni-wuerzburg.de
Wed Jun 23 16:57:20 CEST 2004
Hi folks,
please check out this code (unit). Certainly there is something very strange
going on in handling memory in freepascal. I'm using Free Pascal Compiler
version 1.9.4 [2004/05/30] for i386.
Thanks in advance for replying.
Andreas
{ snip%<************************************************************************
Pascal unit: testObject
Author: Andreas Gros <andreas.gros at biozentrum dot uni-wuerzburg dot de>
}
unit testObject;
interface
uses
SysUtils, Types, Classes, Variants;
procedure test();
type TTestObj = class(TObject)
public
Findex : Integer;
constructor Create(_index : Integer);
end;
implementation
constructor TTestObj.Create(_index : Integer);
begin
Findex := _index;
end;
procedure test();
var list : TList;
i : Integer;
t : TTestObj;
begin
list := TList.Create();
//create 6 TTestObj-ects with ascending indices
for i := 0 to 5 do
begin
list.add(TTestObj.Create(i));
end;
t := TTestObj(list.first());
//writes 0 to stdout
writeln(t.Findex);
FreeAndNil(t);
list.pack();
t := TTestObj(list.first());
{the next line should write 1 to stdout, because the first object was freed,
but the result is 0!!!
it is still the old index, the object is still existing and FreeAndNil as
well as TList.pack have no effect}
writeln(t.Findex);
{ but now the crux: you can't say free again:
an access violation error message turns up}
FreeAndNil(t);
end;
end.
{ snip%<************************************************************************}
testobj.pp:
{ snip%<************************************************************************}
program main;
uses testObject in 'testObject.pas';
begin
test();
end.
{ snip%<************************************************************************}
--
Andreas Gros
Forschungsstation Fabrikschleichach
Uni Wuerzburg
Glashuettenstr. 5
96181 Rauhenebrach
More information about the fpc-pascal
mailing list