Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 39 ยท Derived Types and Pointers

Fortran Pointers, Targets and Allocatables

Understand Fortran pointers and the target attribute, pointer assignment with =>, associated(), allocatable arrays versus pointers, and build a linked list safely.

A Fortran pointer is an alias: a name that can be attached to another variable (its target) or to freshly allocated memory. Pointers are less central than in C because Fortran has allocatable arrays, assumed-shape arguments and derived types. You reach for them when you need aliasing a slice of an array, linking nodes into a list or tree, or switching which object a name refers to.

Pointer and target

A pointer can only point at something declared target (or at memory it allocated itself):

FORTRAN
program pointer_demo
  implicit none
  integer, target  :: a = 10
  integer, pointer :: p => null()

  p => a              ! pointer assignment: p is now an alias for a
  p = 99              ! ordinary assignment changes a
  print *, a          ! prints 99

  print *, associated(p, a)   ! T
  nullify(p)                  ! p now points at nothing
  print *, associated(p)      ! F
end program pointer_demo

Two assignment operators matter. p => a is pointer assignment (rebind the alias). p = 99 is ordinary assignment: it writes through the pointer to the target. Mixing them up is the most common pointer bug.

associated(p) tells you whether the pointer currently points at something. Initialize pointers to null() so the test is meaningful; an undefined pointer status can be neither tested nor used.

Python Stand-in: alias versus rebinding

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 input()), it gets the next line from this box.

Pointers to array sections

A pointer can alias part of an array, with no copy:

FORTRAN
real, target  :: x(10)
real, pointer :: middle(:)

x = [(real(i), i = 1, 10)]
middle => x(4:7)       ! middle(1) is x(4)
middle = 0.0           ! zeroes x(4:7)

The pointer's bounds start at 1 unless you set them: middle(0:) => x(4:7) gives lower bound 0. Bounds-remapping also lets you view a one-dimensional array as two-dimensional:

FORTRAN
real, target  :: v(12)
real, pointer :: m(:,:)
m(1:3, 1:4) => v    ! 3 x 4 view of v, no copy

Allocating through a pointer

A pointer can own memory:

FORTRAN
real, pointer :: buf(:)
allocate(buf(1000))
buf = 0.0
! ... use buf ...
deallocate(buf)

Nobody frees this memory automatically. If you lose the only pointer (reassign it or leave the scope) without deallocate, you leak memory. If two pointers alias the same memory and one deallocates, the other dangles and using it is undefined.

Allocatable versus pointer

allocatable pointer
Aliases other data no yes
Freed automatically yes, on leaving scope no, you must deallocate
Can alias an array section no yes
Optimizations better (no aliasing) worse (compiler must assume aliasing)
Use for ordinary dynamic arrays and components linked structures, views, rebinding

The rule: use allocatable unless you need pointer semantics. Allocatable arrays are safer and faster, and modern Fortran lets allocatable components live inside derived types (see derived types).

flowchart LR
    A["need dynamic size?"] -->|yes| B["need to alias or link?"]
    B -->|no| C["allocatable"]
    B -->|yes| D["pointer"]
    A -->|no| E["fixed-size array"]

Pick allocatable first; pointers are the exception.

A singly linked list

Pointers shine for linked structures. A node holds a value and a pointer to the next node of its own type:

FORTRAN
module list_mod
  implicit none

  type :: node
    integer :: value
    type(node), pointer :: next => null()
  end type node

contains

  subroutine push_front(head, v)
    type(node), pointer :: head
    integer, intent(in) :: v
    type(node), pointer :: n
    allocate(n)
    n%value = v
    n%next => head
    head => n
  end subroutine push_front

  subroutine print_list(head)
    type(node), pointer :: head
    type(node), pointer :: cur
    cur => head
    do while (associated(cur))
      write (*, "(i0, 1x)", advance="no") cur%value
      cur => cur%next
    end do
    write (*, *)
  end subroutine print_list

  subroutine free_list(head)
    type(node), pointer :: head
    type(node), pointer :: cur, nxt
    cur => head
    do while (associated(cur))
      nxt => cur%next
      deallocate(cur)
      cur => nxt
    end do
    head => null()
  end subroutine free_list

end module list_mod

After push_front(head, 3), push_front(head, 2), push_front(head, 1), print_list writes 1 2 3, because each push puts the new node at the front. Note how free_list saves cur%next before deallocating cur.

Python Stand-in: the same linked list

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 input()), it gets the next line from this box.

Procedure pointers

A pointer can also refer to a procedure, selecting behavior at run time:

FORTRAN
procedure(fn), pointer :: op => null()
op => my_square
print *, op(3.0)

Here fn is an interface as in interfaces and generic procedures.

Common mistakes

  • Using = where you meant => (writing through instead of rebinding), or the reverse.
  • Pointing at a variable that is not target; the compiler may reject it or optimize assuming no alias.
  • Leaving pointers undefined. Initialize with => null().
  • Deallocating a pointer that points at a target, not at allocated memory.
  • Forgetting to free: leaks add up in long runs.
  • Using a pointer to a local variable after the procedure returned (dangling).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does p => a do?

    => is pointer assignment. It rebinds the pointer to a target.
  2. 2. Which attribute must a variable have to be pointed at?

    Only objects declared target (or memory allocated through a pointer) can be the target of a pointer.
  3. 3. When should you prefer allocatable over pointer?

    Allocatables are freed automatically and allow better optimization, so use them unless you need pointer semantics.
  4. 4. What does associated(p) report?

    associated tests pointer association status. Initialize pointers to null() so it is well defined.

Summary

  • A pointer is an alias; => rebinds it, = writes through it.
  • Targets must be declared target; test with associated, clear with nullify.
  • Pointers can alias array sections and remap bounds without copying.
  • Prefer allocatable; use pointers for linked structures and views.
  • Free what you allocate through pointers and avoid dangling references.

Next: Type-bound procedures