Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 36 ยท Records, Arrays and Pointers

Pointers and Dynamic Memory in Pascal

Understand Pascal pointers: typed pointers, the ^ and @ operators, New and Dispose, nil and Assigned, GetMem and FreeMem, memory leaks, dangling pointers and pointer arithmetic.

Every variable you have used so far lives in memory that the compiler manages for you. A pointer is a variable that holds a memory address instead of a value, which lets a program create data on demand, share data without copying it and build structures such as linked lists and trees. Pointers are powerful and easy to misuse, so this lesson also shows the classic ways they go wrong.

Pascal code is read-only; the runnable demos are C stand-ins, since C pointers behave almost identically.

Pointer types and the ^ operator

A typed pointer is declared with ^ followed by the type it points to:

PASCAL
program Pointers;

type
  PInteger = ^Integer;   { P prefix = pointer type, by convention }

var
  p: PInteger;

begin
  New(p);                { allocate an Integer on the heap }
  p^ := 42;              { p^ is "the thing p points to" }
  WriteLn(p^);           { 42 }
  p^ := p^ + 1;
  WriteLn(p^);           { 43 }
  Dispose(p);            { give the memory back }
end.
  • p holds an address; p^ (the dereference) is the Integer stored at that address.
  • New(p) allocates a new Integer on the heap, the area of memory for data whose lifetime you control, and stores its address in p.
  • Dispose(p) releases it. Every New needs exactly one matching Dispose.
flowchart LR
    P["p (pointer variable)<br/>address 0x1F40"] -->|points to| H["heap cell<br/>value 43"]

Figure: the pointer variable holds an address; the value lives elsewhere.

The address operator and nil

@x gives the address of an existing variable, and a pointer can point at it:

PASCAL
var
  n: Integer;
  q: ^Integer;       { an anonymous pointer type is allowed here }
begin
  n := 10;
  q := @n;
  q^ := 99;
  WriteLn(n);        { 99: changing q^ changed n }
end.

The special value nil means "points to nothing". Initialize pointers to nil and test them before use:

PASCAL
var
  p: PInteger;
begin
  p := nil;
  if p = nil then
    WriteLn('no value yet');
  if Assigned(p) then          { same test, reversed: p <> nil }
    WriteLn(p^);
end.

Dereferencing nil crashes the program (an access violation or "Runtime error 216"). Always check.

Pointers to records

Pointers to records are everywhere, because you reach a field with p^.Field, or in Delphi and Free Pascal simply p.Field:

PASCAL
type
  PPerson = ^TPerson;
  TPerson = record
    Name: string;
    Age: Integer;
  end;

var
  who: PPerson;
begin
  New(who);
  who^.Name := 'Ada';
  who^.Age := 36;
  WriteLn(who^.Name);
  Dispose(who);       { also frees the string field it manages }
end.

Notice that PPerson is declared before TPerson. Pascal allows a pointer type to refer to a type that is declared later in the same type block, which is essential for linked structures (see Linked Structures with Pointers).

GetMem and FreeMem

New and Dispose know the size of the type. For a block whose size you decide at run time, use an untyped Pointer with GetMem and FreeMem:

PASCAL
var
  buffer: Pointer;
  bytes: PByte;
  i: Integer;
begin
  GetMem(buffer, 4);              { 4 bytes }
  bytes := buffer;
  for i := 0 to 3 do
    bytes[i] := i * 10;           { indexing a PByte needs {$POINTERMATH ON} }
  FreeMem(buffer);
end.

Indexing a pointer like an array requires {$POINTERMATH ON} (on by default for PByte in Delphi and in Free Pascal's delphi mode); otherwise use Inc(bytes) and bytes^. With PChar, PByte and friends, Inc(p) advances by the size of the pointed-to type. Plain Pointer cannot be dereferenced or incremented, because it has no element size.

The classic pointer bugs

Bug What happens How to avoid it
Memory leak You call New but never Dispose; memory use grows until the program ends Match every allocation with one release
Dangling pointer You use a pointer after Dispose; the memory may now belong to something else Set the pointer to nil right after Dispose
Double free Dispose called twice on the same address Set to nil; Dispose(nil) is harmless in some cases but wrong in principle
nil dereference p^ while p = nil Test Assigned(p)
Wild pointer Using an uninitialized pointer Initialize to nil; globals start as nil but locals do not
PASCAL
Dispose(p);
p := nil;          { good habit: no dangling pointer left }

Free Pascal can find leaks for you: compile with -gh (heaptrc) and the program prints a report of unreleased blocks when it ends. Delphi has ReportMemoryLeaksOnShutdown := True.

When do you need pointers today?

In everyday Delphi code you rarely write raw pointers. Dynamic arrays, strings, classes and generic lists hide them for you. You still meet pointers when you:

  • build your own linked structures (lists, trees, graphs);
  • call operating-system APIs that take buffers;
  • pass Pointer data to callbacks (for example Tag or Data fields);
  • read the internals of classes, which are references to heap objects.

Understanding them explains why b := a for classes copies a reference, not the object, which Chapter 6 depends on.

Stand-ins in C

These programs are C: malloc/free correspond to New/Dispose, *p to p^, &x to @x, NULL to nil.

C C stand-in: New, p^, @x and Dispose

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C C stand-in: pointer to a record

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does p^ mean when p is a pointer variable?

    The caret after a pointer variable dereferences it: it is the object the pointer points to.
  2. 2. What does @x produce?

    The @ operator gives the address of an existing variable, which can be stored in a pointer.
  3. 3. Every call to New should be matched by...

    Heap memory from New is not freed automatically. Without Dispose you leak memory.
  4. 4. Which is a dangling pointer?

    After Dispose the address is invalid but the pointer still holds it. Setting it to nil afterwards avoids misuse.

Summary

  • A pointer holds an address; ^ declares and dereferences, @ takes an address, nil means nothing.
  • New/Dispose manage typed heap memory; GetMem/FreeMem manage raw blocks.
  • Avoid leaks, dangling pointers and nil dereferences: pair every allocation with a release and set pointers to nil.
  • Pointer types may refer to types declared later in the same type block.

Next: Linked Structures with Pointers