Steve
Steve

Reputation: 2520

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 String)? Should I call Data.Str := ''; before calling Dispose?

Thanks!

Upvotes: 7

Views: 1589

Answers (4)

himself
himself

Reputation: 4884

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

Upvotes: 12

David Heffernan
David Heffernan

Reputation: 613461

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;

Upvotes: 10

Marco van de Voort
Marco van de Voort

Reputation: 26361

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

Upvotes: 0

kovarex
kovarex

Reputation: 1830

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

Upvotes: 0

Related Questions