【发布时间】:2013-03-31 15:32:03
【问题描述】:
我遇到了一个 Delphi 7 应用程序(CLX)的内存泄漏问题,代码如下:
unit Unit2;
interface
uses ECRClass, ECR_Text, SysUtils, Types, Classes, Variants, Math;
type tLeakClass = class
private
fsType : integer;
public
fsPrinter : TECR_Class;
published
constructor Create (AOwner : TComponent);
destructor Destroy();
end;
implementation
constructor tLeakClass.Create (AOwner : TComponent);
begin
fsPrinter := TECR_Text.Create(AOwner);
end;
destructor tLeakClass.Destroy();
begin
fsPrinter.Free
end;
end.
对象fsPrinter即使在主窗体(TForm)关闭时被释放,结果也会泄露:
unit Unit1;
interface
uses
SysUtils, Types, Classes, Variants, QTypes, QGraphics, QControls, QForms,
QDialogs, QStdCtrls, Unit2;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
tleak : tLeakClass;
end;
var
Form1: TForm1;
implementation
{$R *.xfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
tLeak := tLeakClass.Create(Self);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
tleak.Free
end;
end.
这是 FastMM4 的泄漏报告:
A memory block has been leaked. The size is: 740
This block was allocated by thread 0xBA8, and the stack trace (return addresses) at the time was:
402F1C [system.pas][System][@GetMem][2439]
403C77 [system.pas][System][TObject.NewInstance][8360]
404012 [system.pas][System][@ClassCreate][9019]
502F15 [ECR_Text.pas][ECR_Text][TECR_Text.Create][101]
403C80 [system.pas][System][TObject.NewInstance][8360]
404012 [system.pas][System][@ClassCreate][9019]
5030C6 [Unit2.pas][Unit2][tLeakClass.Create][24]
43856C [QStdCtrls.pas][QStdCtrls][2863]
503300 [Unit1.pas][Unit1][TForm1.Button1Click][30]
447076 [QControls.pas][QControls][TControl.Click][1977]
43858C [QStdCtrls.pas][QStdCtrls][TButton.Click][2871]
The block is currently used for an object of class: TECR_Text
Here 您可以下载代表问题的项目的完整SSCCE 示例(单击按钮运行示例并关闭表单)。
为什么fsPrinter 对象会泄漏?我怎样才能避免泄漏?
【问题讨论】:
-
如果您多次单击该按钮,您将覆盖
TLeak字段中对TLeakClass对象的引用,从而将这些对象变为孤立对象。您只需要保留对所有这些对象的引用,或者在创建新对象之前调用TLeak.Free。 -
不,我只点击了一次。这只是说明问题的一个例子。您必须单击一次按钮,然后关闭表单...
-
好吧,那么使用
OnCreate表单事件可能会更好。 -
这是一个更好的例子。做得好。对于构建非常小的 SSCCE,我的建议是制作控制台应用程序。
标签: delphi memory-leaks delphi-7 kylix clx