Memory management in Pascal
last modified November 18, 2026 Free Pascal 3.2.2
A Pascal program uses two kinds of memory. The stack holds local variables and
parameters and is released automatically when a routine returns. The heap holds
values whose lifetime is controlled by the program: records allocated with
New, buffers allocated with GetMem, objects created
with Create, and the internal storage of strings and dynamic
arrays. This article explains the two regions, allocates and frees typed and
raw memory, manages object ownership with try..finally, uses
interface reference counting, and finds leaks with the -gh
heaptrc report.
Stack and heap
Every call pushes a stack frame that holds the parameters, the local variables, and the return address. The frame disappears when the routine returns, which is why a local variable must never be returned by address. The heap is a larger region managed by the run-time library: a value allocated there stays alive until it is explicitly freed, regardless of which routine allocated it. Dynamic arrays and long strings live on the heap even though the variable that refers to them is a local on the stack.
The distinction explains two common bugs. Returning a pointer to a local variable gives a dangling pointer, because the stack frame is gone. Allocating on the heap and losing the last pointer gives a leak, because nothing can free the block. The rest of the article uses the heap deliberately and pairs every allocation with a release.
New and Dispose
New(P) allocates a block the size of the type that P
points to, stores its address in P, and initializes any managed
fields such as strings and dynamic arrays. Dispose(P) finalizes
those fields and returns the block to the heap. The pointer variable itself is
not changed, so it still holds the old address after the release and must not
be dereferenced again.
program newdispose;
{$mode objfpc}{$H+}
type
PPerson = ^TPerson;
TPerson = record
Name: string;
Age: Integer;
end;
var
P: PPerson;
begin
New(P);
try
P^.Name := 'Ada';
P^.Age := 36;
WriteLn(P^.Name, ' is ', P^.Age);
WriteLn('record size: ', SizeOf(TPerson));
finally
Dispose(P);
end;
WriteLn('pointer is nil: ', P = nil);
end.
The record contains a string, so the 16 bytes reported by
SizeOf are the pointer-sized string reference plus the integer and
padding; the characters live in a separate heap block owned by the string.
Dispose releases both. The final line prints
FALSE, which shows that Dispose does not clear the
variable; assigning P := nil after the release makes the invalid
state visible and turns a later accidental use into a nil dereference rather
than a silent corruption.
$ fpc -gl newdispose.pas $ ./newdispose Ada is 36 record size: 16 pointer is nil: FALSE
Raw memory with GetMem and FreeMem
GetMem(P, Size) allocates Size bytes and stores the
address in the untyped pointer P. It does not know the type, so it
neither initializes the bytes nor finalizes anything on release.
FreeMem(P) returns the block, and FreeMem(P, Size)
checks that the size matches in debugging builds. Raw memory is appropriate for
buffers that are read from a file or passed to a C function, where the layout
is defined by bytes rather than by a Pascal type.
program rawmem;
{$mode objfpc}{$H+}
var
Raw: Pointer;
P: PInteger;
begin
GetMem(Raw, SizeOf(Integer));
try
P := PInteger(Raw);
P^ := 1234;
WriteLn('value: ', P^);
WriteLn('bytes: ', SizeOf(Integer));
finally
FreeMem(Raw);
end;
end.
The cast PInteger(Raw) gives the untyped block an interpretation as
one integer. Nothing stops the program from writing past the four bytes, and
nothing initializes them, so the programmer is responsible for both the size
and the contents. New and Dispose are safer for typed
data because the compiler supplies the size and the finalization; raw memory is
for cases where the size is computed at run time or the layout comes from
outside Pascal.
$ fpc -gl rawmem.pas $ ./rawmem value: 1234 bytes: 4
Objects and try..finally
A class instance is created with a constructor and released with
Free. The constructor allocates the object and runs the
initialization; the destructor runs the cleanup and releases the memory.
Free checks for nil, so calling it on a nil reference
is safe. FreeAndNil calls Free and then sets the
variable to nil, which prevents a second release through the same
variable.
program objects;
{$mode objfpc}{$H+}
uses SysUtils, Classes;
var
List: TStringList;
begin
List := TStringList.Create;
try
List.Add('alpha');
List.Add('beta');
WriteLn('items: ', List.Count);
finally
List.Free;
end;
List := nil;
List.Free;
WriteLn('Free on nil is safe');
List := TStringList.Create;
List.Add('gamma');
FreeAndNil(List);
WriteLn('after FreeAndNil: ', List = nil);
end.
The first block is the standard ownership pattern: create, use, free in
finally, so an exception between creation and the end still
releases the object. The middle block shows that Free accepts a
nil reference, which removes the need for an explicit if List <> nil
guard. The last block shows FreeAndNil, after which the variable
compares equal to nil. Calling Free twice on the same
non-nil object is an error, not a no-op.
$ fpc -gl objects.pas $ ./objects items: 2 Free on nil is safe after FreeAndNil: TRUE
Interface reference counting
An object that implements an interface and descends from
TInterfacedObject is released automatically when the last
interface reference goes away. Each assignment to an interface variable
increments the reference count, and each release or reassignment decrements
it; when the count reaches zero, the object's destructor runs. This is the
mechanism behind the interface lifetime rules described in the
interfaces article.
program iface;
{$mode objfpc}{$H+}
uses SysUtils;
type
ILogger = interface
procedure Log(const Msg: string);
end;
TConsoleLogger = class(TInterfacedObject, ILogger)
public
procedure Log(const Msg: string);
destructor Destroy; override;
end;
procedure TConsoleLogger.Log(const Msg: string);
begin
WriteLn('log: ', Msg);
end;
destructor TConsoleLogger.Destroy;
begin
WriteLn('logger destroyed');
inherited Destroy;
end;
var
L: ILogger;
begin
L := TConsoleLogger.Create;
L.Log('first message');
L := nil;
WriteLn('after release');
end.
The variable L is the only reference to the object. Assigning
nil drops the count to zero and calls the destructor before the
next line runs, which is why logger destroyed appears before
after release. There is no Free call, and calling one
would be wrong: the interface owns the object. A class that implements an
interface without TInterfacedObject must implement the three
methods of IInterface itself if it wants the same lifetime.
$ fpc -gl iface.pas $ ./iface log: first message logger destroyed after release
Managed fields
Strings, dynamic arrays, and interfaces are managed types: the compiler emits
code that initializes them, copies them, and finalizes them. A local variable
of such a type is finalized when the routine returns, and a record field is
finalized when the record itself is finalized. The program rarely calls
Finalize directly, but doing so releases the contents of a
variable without releasing the variable itself.
program managed;
{$mode objfpc}{$H+}
type
TBuffer = record
Data: array of Integer;
Name: string;
end;
var
B: TBuffer;
I: Integer;
begin
SetLength(B.Data, 3);
for I := 0 to 2 do
B.Data[I] := (I + 1) * 10;
B.Name := 'sample';
WriteLn('name: ', B.Name);
WriteLn('length: ', Length(B.Data));
WriteLn('last: ', B.Data[High(B.Data)]);
B.Name := '';
B.Data := nil;
WriteLn('after release: ', Length(B.Data), ' ', B.Name = '');
end.
Assigning nil to the dynamic array and an empty string to the
name releases their heap blocks immediately, because the reference count of
each drops to zero. The record variable itself stays on the stack and is
reused. This automatic management is why a record with managed fields cannot
be written to a file with a raw BlockWrite: the bytes contain
pointers, not the character data, and the pointers are meaningless in another
process.
$ fpc -gl managed.pas $ ./managed name: sample length: 3 last: 30 after release: 0 TRUE
Finding leaks with heaptrc
The -gh switch links the heaptrc unit, which records every heap
allocation and prints a report at exit. The report lists the total blocks
allocated and freed, the blocks still unfreed, the heap size, and a call trace
for each leak. A program that releases everything prints a report with zero
unfreed blocks. The example deliberately forgets to free a string list.
program leak;
{$mode objfpc}{$H+}
uses SysUtils, Classes;
var
List: TStringList;
begin
List := TStringList.Create;
List.Add('this string is never freed');
WriteLn('created a list with ', List.Count, ' item');
end.
The program prints its normal line and then the heaptrc summary. Two blocks
are unfreed: the TStringList object and its internal storage. A full build prints a call trace for each unfreed block after the summary,
pointing at the Create call in the main block. The exact counts depend on the RTL version and on the units
linked, but the difference between allocated and freed blocks is the number to
watch. Compiling with -gh in a test run and without it for release
is the usual arrangement.
$ fpc -gl -gh leak.pas $ ./leak created a list with 1 item Heap dump by heaptrc unit of /tmp/opencode/pas-work/a38/leak 25 memory blocks allocated : 1860/1872 23 memory blocks freed : 1652/1664 2 unfreed memory blocks : 208 True heap size : 393216 True free heap : 392576 Should be : 392624
Next steps
The pointers article introduces the address
syntax that New and GetMem return, and the
linked lists article uses heap nodes with
explicit Dispose. The
exceptions article explains why cleanup
belongs in finally, and the
interfaces article describes reference
counting in more detail. The
bit manipulation article works with
fixed-size integers that need no heap at all.
Source
Free Pascal Reference guide: pointers
In this article we separated stack and heap storage, allocated and released
typed records with New and Dispose, used raw memory
with GetMem and FreeMem, managed objects with
FreeAndNil and finally, relied on interface reference
counting, released managed fields, and read the heaptrc leak report. The series
continues with bit manipulation in Pascal.
Author
List all Pascal tutorials.