Modula-2 pointers and the heap
last modified November 27, 2026 Modula-2
The variables of the earlier articles are declared in the source, and the
compiler reserves their storage. A program that does not know in advance how
many values it will hold creates them at run time instead, in a memory area
called the heap. A pointer holds the address of such a value. This article
allocates and frees heap storage with NEW and
DISPOSE, uses NIL, points to records, and links
records with pointers.
A pointer to an integer
A pointer type is declared with POINTER TO and the type of the
values it points to. NEW(p) allocates one such value on the
heap and stores its address in p; p^ is the value
itself, and DISPOSE(p) returns the storage.
MODULE first;
FROM InOut IMPORT WriteString, WriteInt, WriteLn;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;
TYPE
IntPtr = POINTER TO INTEGER;
VAR
p: IntPtr;
BEGIN
NEW(p);
p^ := 42;
WriteString("p^ = "); WriteInt(p^, 0); WriteLn;
p^ := p^ * 2;
WriteString("p^ = "); WriteInt(p^, 0); WriteLn;
DISPOSE(p)
END first.
p is a variable of type IntPtr, and
p^, read "p dereferenced", is the INTEGER it
points to. p^ is used like any integer variable: it is assigned,
read and doubled. In PIM Modula-2, NEW and
DISPOSE are shorthands that the compiler turns into calls of
ALLOCATE and DEALLOCATE, which the program imports
from Storage. Modula-2 has no garbage collector: storage taken
with NEW stays taken until the program disposes of it.
$ gm2 first.mod -o first $ ./first p^ = 42 p^ = 84
NEW needs ALLOCATE
Because NEW is translated into a call, the procedure it calls
must be visible. The next program forgets the import from
Storage.
MODULE noalloc; FROM InOut IMPORT WriteInt, WriteLn; TYPE IntPtr = POINTER TO INTEGER; VAR p: IntPtr; BEGIN NEW(p); p^ := 42; WriteInt(p^, 0); WriteLn END noalloc.
The compiler looks for a procedure named ALLOCATE in the scope
of the call and does not find one. DISPOSE needs
DEALLOCATE in the same way. A program may supply its own
procedures with these names, for example to count allocations, and
NEW then calls them.
$ gm2 noalloc.mod -o noalloc
noalloc.mod:11:3: error: In program module ‘noalloc’: ALLOCATE procedure not found for NEW substitution
11 | NEW(p);
| ^~~
noalloc.mod:11:3: error: unknown symbol ‘ALLOCATE’
noalloc.mod:14:12: error: the following unknown symbols in module ‘noalloc’ were unresolved: ALLOCATE
14 | END noalloc.
| ^
What NEW does
ALLOCATE takes the pointer variable and the number of bytes to
allocate. TSIZE from the SYSTEM module gives the
size of a type, so a call of NEW can be written out in full.
MODULE allocate;
FROM InOut IMPORT WriteString, WriteInt, WriteCard, WriteLn;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;
FROM SYSTEM IMPORT TSIZE;
TYPE
IntPtr = POINTER TO INTEGER;
RealPtr = POINTER TO REAL;
VAR
p: IntPtr;
r: RealPtr;
BEGIN
ALLOCATE(p, TSIZE(INTEGER));
p^ := 7;
WriteString("p^ = "); WriteInt(p^, 0); WriteLn;
DEALLOCATE(p, TSIZE(INTEGER));
NEW(r);
WriteString("bytes for an INTEGER: "); WriteCard(TSIZE(INTEGER), 0); WriteLn;
WriteString("bytes for a REAL: "); WriteCard(TSIZE(REAL), 0); WriteLn;
WriteString("bytes for a pointer: "); WriteCard(TSIZE(RealPtr), 0); WriteLn;
DISPOSE(r)
END allocate.
ALLOCATE(p, TSIZE(INTEGER)) is what NEW(p) means,
and DEALLOCATE(p, TSIZE(INTEGER)) is what
DISPOSE(p) means. NEW is shorter and cannot get
the size wrong, so programs use it. An integer takes 4 bytes and a real 8;
a pointer takes 8 bytes on a 64-bit system, whatever it points to.
$ gm2 allocate.mod -o allocate $ ./allocate p^ = 7 bytes for an INTEGER: 4 bytes for a REAL: 8 bytes for a pointer: 8
Two pointers to one value
Assigning a pointer copies the address, not the value. After
q := p both variables point to the same integer, and a change
through one is seen through the other.
MODULE alias;
FROM InOut IMPORT WriteString, WriteInt, WriteLn;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;
TYPE
IntPtr = POINTER TO INTEGER;
VAR
p, q: IntPtr;
PROCEDURE Show(label: ARRAY OF CHAR; a, b: IntPtr);
BEGIN
WriteString(label);
WriteString(": p^ = "); WriteInt(a^, 0);
WriteString(", q^ = "); WriteInt(b^, 0);
WriteLn
END Show;
BEGIN
NEW(p);
p^ := 1;
q := p;
q^ := 7;
Show("shared", p, q);
NEW(q);
q^ := p^;
q^ := q^ + 1;
Show("copied", p, q);
DISPOSE(p);
DISPOSE(q)
END alias.
In the first part q and p share one integer, so
q^ := 7 also changes p^. In the second part
NEW(q) gives q a value of its own, and
q^ := p^ copies the integer, not the address; incrementing
q^ then leaves p^ alone. Each NEW is
matched by one DISPOSE. Had the first part ended with
DISPOSE(q) as well, the shared integer would be freed twice.
$ gm2 alias.mod -o alias $ ./alias shared: p^ = 7, q^ = 7 copied: p^ = 7, q^ = 8
Pointer types are distinct
Two pointer types declared separately are different types, even when they point to the same type. A pointer of one cannot be assigned to a variable of the other.
MODULE ptrtypes; FROM Storage IMPORT ALLOCATE, DEALLOCATE; TYPE Count = POINTER TO INTEGER; Score = POINTER TO INTEGER; VAR c: Count; s: Score; BEGIN NEW(c); s := c END ptrtypes.
Count and Score both point to integers, but the
compiler keeps them apart, as it keeps two separately declared array types
apart. The rule lets a program give pointers to different kinds of data
their own types, so they cannot be mixed by mistake.
$ gm2 ptrtypes.mod -o ptrtypes
ptrtypes.mod:14:5: error: assignment designator ‘s’ of type ‘Score’'' cannot be assigned with'' a ‘Count’ ‘c’
14 | s := c
| ~~^~~~
ptrtypes.mod:14:5: error: ‘Score’ and ‘Count’ are assignment incompatible
The value NIL
NIL is a pointer value that points to nothing. It can be
assigned to a variable of any pointer type and compared with
= and #.
MODULE nil;
FROM InOut IMPORT WriteString, WriteInt, WriteLn;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;
TYPE
IntPtr = POINTER TO INTEGER;
VAR
p: IntPtr;
PROCEDURE Show(ptr: IntPtr);
BEGIN
IF ptr = NIL THEN
WriteString("nothing")
ELSE
WriteInt(ptr^, 0)
END;
WriteLn
END Show;
BEGIN
p := NIL;
Show(p);
NEW(p);
p^ := 12;
Show(p);
DISPOSE(p);
Show(p)
END nil.
Show tests its parameter before it dereferences it. The pointer
starts as NIL, then points to a new integer, and is
NIL again after DISPOSE: GNU Modula-2's
DEALLOCATE sets the variable it frees to NIL. A
pointer variable that was never assigned is not NIL; it holds
an undefined address, so programs set pointers to NIL
explicitly.
$ gm2 nil.mod -o nil $ ./nil nothing 12 nothing
Dereferencing NIL
Reading or writing through a NIL pointer is an error. GNU
Modula-2 catches it at run time, even in a build without checks.
MODULE nilderef;
FROM InOut IMPORT WriteString, WriteInt, WriteLn;
TYPE
IntPtr = POINTER TO INTEGER;
VAR
p: IntPtr;
BEGIN
p := NIL;
WriteString("reading p^");
WriteLn;
WriteInt(p^, 0);
WriteLn
END nilderef.
The first line is printed, and then the program stops with "invalid address
referenced" and exit status 134 instead of crashing with a bare segmentation
fault. With -fsoft-check-all the compiler adds a test before
every dereference and names the pointer in the message.
$ gm2 nilderef.mod -o nilderef $ ./nilderef reading p^ RTExceptions.mod:650:35: In invalidloc RTExceptions.mod:650:35:invalid address referenced Aborted (core dumped) $ echo $? 134
Pointers to records
Most pointers point to records. A field of the record is reached with
p^.field, and WITH p^ DO opens all fields of the
record that p points to.
MODULE record;
FROM InOut IMPORT WriteString, WriteInt, WriteLn;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;
TYPE
Point = RECORD
x, y: INTEGER
END;
PointPtr = POINTER TO Point;
VAR
p: PointPtr;
BEGIN
NEW(p);
p^.x := 3;
p^.y := 4;
WriteString("("); WriteInt(p^.x, 0);
WriteString(", "); WriteInt(p^.y, 0); WriteString(")");
WriteLn;
WITH p^ DO
x := x * 10;
y := y * 10;
WriteString("("); WriteInt(x, 0);
WriteString(", "); WriteInt(y, 0); WriteString(")")
END;
WriteLn;
DISPOSE(p)
END record.
p^ is the whole record and p^.x one field of it.
Inside WITH p^ the field names stand alone, as in the
records article. The record exists only on
the heap; the program reaches it through the 8 bytes of p.
$ gm2 record.mod -o record $ ./record (3, 4) (30, 40)
Creating values in procedures
A value on the heap outlives the procedure that created it. A function procedure may therefore allocate a record and return a pointer to it, which PIM Modula-2 allows, since a pointer is a simple type.
MODULE make;
FROM InOut IMPORT WriteString, WriteInt, WriteLn;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;
TYPE
Point = RECORD
x, y: INTEGER
END;
PointPtr = POINTER TO Point;
VAR
a, b: PointPtr;
PROCEDURE MakePoint(x, y: INTEGER): PointPtr;
VAR
p: PointPtr;
BEGIN
NEW(p);
p^.x := x;
p^.y := y;
RETURN p
END MakePoint;
PROCEDURE Move(p: PointPtr; dx, dy: INTEGER);
BEGIN
INC(p^.x, dx);
INC(p^.y, dy)
END Move;
PROCEDURE WritePoint(p: PointPtr);
BEGIN
WriteString("("); WriteInt(p^.x, 0);
WriteString(", "); WriteInt(p^.y, 0); WriteString(")");
WriteLn
END WritePoint;
PROCEDURE FreePoint(VAR p: PointPtr);
BEGIN
DISPOSE(p)
END FreePoint;
BEGIN
a := MakePoint(1, 2);
b := MakePoint(-5, 0);
Move(a, 10, 10);
WritePoint(a);
WritePoint(b);
FreePoint(a);
FreePoint(b);
IF (a = NIL) AND (b = NIL) THEN
WriteString("both freed"); WriteLn
END
END make.
MakePoint allocates a point, fills it in and returns its
address; its local variable p disappears, but the record does
not. Move takes the pointer as a value parameter: the address
is copied, so the procedure changes the caller's record through it.
FreePoint needs a VAR parameter, because
DISPOSE sets the caller's variable to NIL.
$ gm2 make.mod -o make $ ./make (11, 12) (-5, 0) both freed
Arrays of pointers
An array of pointers holds the addresses of records, not the records. Two elements are exchanged by exchanging two pointers, however large the records are.
MODULE table;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;
FROM SYSTEM IMPORT TSIZE;
FROM Strings IMPORT Assign;
CONST
N = 4;
TYPE
Name = ARRAY [0..31] OF CHAR;
City = RECORD
name: Name;
population: CARDINAL
END;
CityPtr = POINTER TO City;
VAR
cities: ARRAY [1..N] OF CityPtr;
i, j: CARDINAL;
t: CityPtr;
PROCEDURE NewCity(name: ARRAY OF CHAR; population: CARDINAL): CityPtr;
VAR
c: CityPtr;
BEGIN
NEW(c);
Assign(c^.name, name);
c^.population := population;
RETURN c
END NewCity;
BEGIN
cities[1] := NewCity("Bratislava", 475000);
cities[2] := NewCity("Zurich", 436000);
cities[3] := NewCity("Vienna", 2006000);
cities[4] := NewCity("Brno", 397000);
FOR i := 1 TO N - 1 DO
FOR j := i + 1 TO N DO
IF cities[j]^.population > cities[i]^.population THEN
t := cities[i]; cities[i] := cities[j]; cities[j] := t
END
END
END;
FOR i := 1 TO N DO
WITH cities[i]^ DO
WriteCard(population, 9); WriteString(" "); WriteString(name); WriteLn
END
END;
WriteString("bytes per record: "); WriteCard(TSIZE(City), 0); WriteLn;
WriteString("bytes per pointer: "); WriteCard(TSIZE(CityPtr), 0); WriteLn;
FOR i := 1 TO N DO
DISPOSE(cities[i])
END
END table.
NewCity creates one record on the heap and copies the name
into it with Assign from the
strings article. The nested loops order the
array by population, largest first; each exchange moves three 8-byte
pointers instead of three 36-byte records. WITH cities[i]^
opens the record the element points to. At the end every record is
disposed of separately.
$ gm2 table.mod -o table $ ./table 2006000 Vienna 475000 Bratislava 436000 Zurich 397000 Brno bytes per record: 36 bytes per pointer: 8
Dangling pointers
DISPOSE sets only its own argument to NIL. Any
other pointer to the same value still holds the old address. Such a pointer
is called dangling, and using it is a bug that the compiler does not catch.
MODULE dangling;
FROM InOut IMPORT WriteString, WriteInt, WriteLn;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;
TYPE
IntPtr = POINTER TO INTEGER;
VAR
p, q, r: IntPtr;
BEGIN
NEW(p);
p^ := 5;
q := p;
DISPOSE(p);
IF p = NIL THEN WriteString("p is NIL") END; WriteLn;
IF q # NIL THEN WriteString("q is not NIL") END; WriteLn;
NEW(r);
r^ := 99;
WriteString("q^ = "); WriteInt(q^, 0); WriteLn;
IF q = r THEN
WriteString("q and r point to the same block"); WriteLn
END;
DISPOSE(r)
END dangling.
q is a copy of p. After DISPOSE(p)
the block is free, but q still points to it. The next
NEW reuses the block for r, so reading
q^ shows the 99 written through r. In a larger
program the block could hold part of an unrelated record, and writing
through q would corrupt it. -fsoft-check-all does
not detect this either: the rule is to forget every copy of a pointer when
the value is disposed of.
$ gm2 dangling.mod -o dangling $ ./dangling p is NIL q is not NIL q^ = 99 q and r point to the same block
Records that point to records
A record may contain a pointer to a record of its own type. The pointer type
is then declared before the record; Modula-2 allows POINTER TO
a type declared later in the same TYPE section.
MODULE chain;
FROM InOut IMPORT WriteString, WriteInt, WriteLn;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;
TYPE
NodePtr = POINTER TO Node;
Node = RECORD
value: INTEGER;
next: NodePtr
END;
VAR
head, p, q: NodePtr;
i: INTEGER;
BEGIN
head := NIL;
FOR i := 1 TO 5 DO
NEW(p);
p^.value := i * i;
p^.next := head;
head := p
END;
p := head;
WHILE p # NIL DO
WriteInt(p^.value, 4);
p := p^.next
END;
WriteLn;
p := head;
WHILE p # NIL DO
q := p^.next;
DISPOSE(p);
p := q
END;
head := NIL;
WriteString("all nodes freed"); WriteLn
END chain.
Each Node holds a value and the address of the next node. The
first loop creates five nodes and puts each one in front of the chain, so
the last square comes first. The second loop follows the
next pointers until it reaches NIL. The third
loop frees the nodes; it saves p^.next in q
before DISPOSE(p), because the node cannot be read after it is
freed. This is the basis of the linked
lists and trees covered
later in the series.
$ gm2 chain.mod -o chain $ ./chain 25 16 9 4 1 all nodes freed
Source
Modula-2 language reference at modula2.org
In this article we have declared pointer types, allocated and freed heap
storage with NEW and DISPOSE, shared values
between pointers, used NIL, pointed to records, ordered an
array of pointers, met dangling pointers and linked records into a chain.
The records article covers the records
used here, and the opaque types
article hides a pointer type inside a module.
Author
List all Modula-2 tutorials.