【问题标题】:Delphi TPngImage memory leakDelphi TPNGImage 内存泄漏
【发布时间】:2016-12-25 15:17:28
【问题描述】:

我有一个记录,如下所示:

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.`

有没有办法避免这种泄漏?

【问题讨论】:

  • 根据 Loghman 的建议更改了清算程序,并提供了最低限度的所需代码。泄漏仍然存在。
  • 请提供minimal reproducible example 而不是“所需代码的最低限度”,不管是什么。
  • @Robert - 请开始一个新项目,将代码粘贴到此答案中并尝试编译。您认为不必要的细节使我们无法重现您的问题。请阅读已链接三次的页面以了解其含义。
  • 它远非最小。无论如何,您不会破坏您创建的对象。所以他们被泄露了。很平凡。接受答案。

标签: delphi memory-leaks


【解决方案1】:

在使用SetLength(Cells,0);之前,您必须执行以下代码

  for i := 0 to High(Cells) do
    Cells[i].Image.Free;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 2014-05-14
    相关资源
    最近更新 更多