我有一条记录,如下所示:
TCell = record
Marked: Boolean;
ToBeMarked: Boolean;
Image: TPngImage;
end;
var Cells: array of array of TCell
Cells [n] .Image在某个过程中创建,然后存储供以后使用。每次调用该过程时,都会清除此数组。 但是,在关闭程序时,我仍然会收到内存泄漏报告。
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, pngimage, Vcl.StdCtrls;
type
TCell = record
Marked: Boolean;
ToBeMarked: Boolean;
Image: TPngImage;
end;
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure TestProcedure1;
procedure TestProcedure2(X,Y: Integer);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
Cells: array of array of TCell;
RI_LengthX: Integer;
RI_LengthY: Integer;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
TestProcedure1;
end;
procedure TForm1.TestProcedure1;
var X,Y: Integer;
begin
{ Clearing the array before the new cycle }
for X:=0 to High(Cells) do for Y:=0 to High(Cells[X]) do Cells[X,Y].Image.Free;
SetLength(Cells,0);
{ Creating new array }
RI_LengthX:=10;
RI_LengthY:=10;
SetLength(Cells,RI_LengthX);
for X:=0 to High(Cells) do SetLength(Cells[X],RI_LengthY);
{ Calling the procedure that creates image for every cell }
for X:=0 to RI_LengthX-1 do for Y:=0 to RI_LengthY-1 do TestProcedure2(X,Y);
end;
procedure TForm1.TestProcedure2(X,Y: Integer);
var BaseBMP: TBitmap;
begin
{ Dynamic creation of an image }
BaseBMP:=TBitmap.Create;
BaseBMP.Width:=25;
BaseBMP.Height:=25;
{ Saving image inside a record }
Cells[X,Y].Image:=TPngImage.Create; // Commenting these lines
Cells[X,Y].Image.Assign(BaseBMP); // prevents the leak
BaseBMP.Free;
end;
initialization
ReportMemoryLeaksOnShutdown:=True;
end.`
有没有办法避免这种泄漏?
答案 0 :(得分:7)
在使用SetLength(Cells,0);
之前,您必须执行以下代码
for i := 0 to High(Cells) do
Cells[i].Image.Free;