On Wed, 23 Jun 2004, Andreas Gros wrote:
> 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} Your logic is wrong. FreeAndNil(T) did NOT remove the pointer from the list, the list has a COPY of the pointer . Hence List[0] is still different from Nil after the freeandnil, so Pack() will not remove it. The memory pointed to by the (invalid) pointer is not yet trashed, so the output is by chance 0. You must do List.Remove(t); FreeAndNil(T); the List.pack() is no longer necessary then. Michael. _______________________________________________ fpc-pascal maillist - [EMAIL PROTECTED] http://lists.freepascal.org/mailman/listinfo/fpc-pascal