开发者

Am I creating a memory leak here?

A very simple question:

type

TMyRecord = Record
  Int: Integer;
  Str: String;
end;

PMyRecord = ^TMyRecord;

var
  Data: PMyRecord;
begin
  New(Data);
  Data.Int := 42;
  Data.Str := 'Test';
  Dispose(Data);
end;

My question is, am I creating a memory leak here (with the St开发者_如何转开发ring)? Should I call Data.Str := ''; before calling Dispose?

Thanks!


No, Dispose properly frees strings and dynamic arrays in records, including nested ones. GetMem/FreeMem(Data) would create a memory leak, indeed.


It's a memory leak if an exception is raised in between your allocate/deallocate pairs. It is normal to protect them as such:

New(Data);
Try
  Data.Int := 42;
  Data.Str := 'Test';
Finally
  Dispose(Data);
End;


No you are not, String cleans its own memory itself when it is deleted.


If you want a memory leak, afaik you have to use TP objects :-) They are afaik the only structured types in Delphi that are not initialized/finalized

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜