Sample program to feed listview with typed record data, caused memory leak (records not being freed from heap).
The reason I chose to use own data, is because its very fast. adding 1000 items with several subitems with default Listview.Add item procedure is painful slow.
I never had problem with Delphi before, or Delphi handled the record memory automatically?
Can someone enlighten me on how to properly free the manually allocated memory for the records?
unit FormODLaz;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ComCtrls, LCLIntf, LCLType;
type
PItemRecord = ^TItemRecord;
TItemRecord = packed record
ID: integer;
Name: string;
end;
type
{ TForm1 }
TForm1 = class(TForm)
LV1: TListView;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure LV1Data(Sender: TObject; Item: TListItem);
private
public
end;
var
Form1: TForm1;
IDList: TList;
implementation
{$R *.lfm}
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
function GetItemRecord(index: INTEGER): PItemRecord;
begin
Result := PItemRecord(IDList[index]);
end;
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
var
itm : PItemRecord;
i: Integer;
begin
IDList := TList.Create;
LV1.Items.BeginUpdate;
for i := 1 to 100 do
begin
itm := New(PItemRecord); //<======= memory leak complained here
itm^.ID := i;
itm^.Name := 'Item '+ i.ToString;
IDList.Add(itm);
end;
LV1.Items.Count := IDList.Count;
LV1.Items.EndUpdate;
end;
procedure TForm1.FormDestroy(Sender: TObject);
var
i: Integer;
begin
LV1.Clear;
IDList.Free;
//FreeAndNil(IDList);
end;
procedure TForm1.LV1Data(Sender: TObject; Item: TListItem);
begin
if (Item<>nil) then
with GetItemRecord(Item.Index)^ do
begin
Item.Caption := ID.ToString;
Item.SubItems.Add(Name);
end;
end;
end.