1

I do not understand where are the objects below and how to clear them?

for example:

public

Alist: TStringlist;

..
procedure TForm1.FormCreate(Sender: TObject);
begin
Alist:=Tstringlist.Create;
end;

procedure TForm1. addinstringlist;
var
i: integer;
begin

for i:=0 to 100000 do 
   begin
   Alist.add(inttostr(i), pointer(i));
   end;
end;

procedure TForm1.clearlist;
begin
Alist.clear;

// inttostr(i) are cleared, right? 

// Where are pointer(i)? Are they also cleared ?
// if they are not cleared, how to clear ?

end;



  procedure TForm1. repeat;   //newly added
   var
   i: integer;
   begin
   For i:=0 to 10000 do
       begin
       addinstringlist;
       clearlist;
       end;
   end;   // No problem?

I use Delphi 7. In delphi 7.0 help file, it says:

AddObject method (TStringList)

Description
Call AddObject to add a string and its associated object to the list. 
AddObject returns the index of the new string and object.
Note:   
The TStringList object does not own the objects you add this way. 
Objects added to the TStringList object still exist 
even if the TStringList instance is destroyed. 
They must be explicitly destroyed by the application.

In my procedure Alist.add(inttostr(i), pointer(i)), I did not CREATE any object. Were there objects or not ? how can I clear both inttostr(i) and pointer(i).

Thank you in advance

Lieven Keersmaekers
  • 57,207
  • 13
  • 112
  • 146
Warren
  • 795
  • 1
  • 10
  • 19

1 Answers1

6

There is no need to clear Pointer(I) because the pointer does not reference any object. It is an Integer stored as Pointer.

Advice: if you are not sure does your code leak or not write a simple test and use

ReportMemoryLeaksOnShutDown:= True;

If your code leaks you will get a report on closing the test application.


No the code you added does not leak. If your want to check it write a test like this:

program Project2;

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes;

var
  List: TStringlist;

procedure addinstringlist;
var
  i: integer;
begin

for i:=0 to 100 do
   begin
   List.addObject(inttostr(i), pointer(i));
   end;
end;

procedure clearlist;
begin
   List.clear;
end;

procedure repeatlist;
var
   i: integer;

   begin
   For i:=0 to 100 do
       begin
       addinstringlist;
       clearlist;
       end;
   end;


begin
  ReportMemoryLeaksOnShutDown:= True;
  try
    List:=TStringList.Create;
    repeatlist;
    List.Free;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Try to comment List.Free line to create a memory leak and see what happens.

kludg
  • 27,213
  • 5
  • 67
  • 118
  • Thank you so much. I added a repeat procedure. please see. No problem? how should I test ReportMemoryLeaksOnShutDown:= True;? – Warren Feb 26 '13 at 10:51