Search code examples
lazarusfreepascaltstringlist

TStringList count returns negative number


I want to count the number of items(strings) in the TStringList using the count property. TStringList.Count returns me "-307586000" why ?

Here is my code in Lazarus:

procedure Test;
  var
    list: TStringList;
    vrai: boolean;
    nCol, i: integer;

begin
 vrai := true;
 list.Create;
 nCol := 5;
 for i := 0 to nCol-1 do
   if vrai then
     begin
       list.Add(intToStr(i));
       showmessage(IntToStr(list.Count));
     end;
end;

Thx guys.


Solution

  • You need to change list.Create; to list := TStringList.Create; When you call a constructor via an object variable instead of a class type, the constructor gets called like a normal method. You are not actually creating any TStringList object, so calling list.Add() and list.Count is undefined behavior. You are lucky your code didn't simply crash.

    Also, don't forget to call list.Free; when you are done using list.

    Try this:

    procedure Test;
    var
      list: TStringList;
      vrai: boolean;
      nCol, i: integer;
    begin
      vrai := true;
      list := TStringList.Create;
      try
        nCol := 5;
        for i := 0 to nCol-1 do
        begin
          if vrai then
          begin
            list.Add(IntToStr(i));
            ShowMessage(IntToStr(list.Count));
          end;
        end;
      finally
        list.Free;
      end;
    end;