Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 39 ยท Arrays and Numerics

Allocatable Arrays

Create arrays whose size is chosen at run time with Fortran allocatable arrays: allocate, deallocate, allocated, stat, automatic reallocation on assignment, source, mold and move_alloc.

So far every array had a size fixed in the source code. Real programs rarely know their sizes in advance: how many measurements are in the file? How big is the grid the user asked for? Fortran's answer is the allocatable array: you declare its type and rank now, and give it a size when the program runs. Allocatable arrays are safe, since the compiler frees them automatically, and they are the default choice for dynamic data.

Declaring and allocating

Declare with the allocatable attribute and deferred shape (colons instead of sizes):

FORTRAN
program alloc_demo
  implicit none
  real, allocatable :: x(:)         ! rank 1, size not yet known
  integer :: n, i

  n = 5
  allocate(x(n))                    ! now it has 5 elements
  do i = 1, n
    x(i) = real(i) ** 2
  end do
  print *, x
  deallocate(x)                     ! optional: freed at the end anyway
end program alloc_demo

Before allocate, the array has no storage, and touching it is an error. The number of colons is its rank: a(:, :) is a matrix. You can give bounds: allocate(y(0:n)) or allocate(m(rows, cols)). Several arrays can be allocated at once: allocate(a(n), b(n, n)).

flowchart LR
  A["declared<br/>not allocated"] -->|allocate| B["allocated<br/>has storage"]
  B -->|deallocate| A
  B -->|"end of scope"| C["freed<br/>automatically"]

An allocatable array is either allocated or not; leaving its scope frees it automatically.

allocated, deallocate and stat

allocated(x) tells whether an array has storage. Use it before allocating something that might already have storage, since allocating twice is an error:

FORTRAN
if (.not. allocated(x)) allocate(x(100))
if (allocated(x)) deallocate(x)

Memory may run out. Add stat= to receive a status code instead of crashing, and errmsg= for the text:

FORTRAN
integer :: ierr
character(len=200) :: msg

allocate(big(1000000000), stat=ierr, errmsg=msg)
if (ierr /= 0) then
  print *, "Could not allocate:", trim(msg)
  stop 1
end if

A local allocatable array is freed automatically when its procedure returns, so unlike C there is no leak; call deallocate explicitly only to release memory early.

Python Stand-in (Python): allocate with a check

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.

Automatic allocation on assignment

Since Fortran 2003, assigning to an allocatable array allocates it, or reallocates it to the right shape, so you often need no allocate at all:

FORTRAN
real, allocatable :: y(:)

y = [1.0, 2.0, 3.0]          ! y is allocated with 3 elements
y = [y, 4.0]                 ! grows: 4 elements
y = pack(y, y > 1.5)         ! shrinks to the selected elements
y = linspace_result          ! sized from the right-hand side

This is the easy way to grow an array: y = [y, new_value]. It copies the array each time, so it is fine for small lists but slow if done millions of times; for that, allocate extra capacity and track a count yourself.

Be careful with array sections. y(:) = ... assigns into the existing storage without reallocating and requires matching size, while y = ... reallocates. Some compilers can be told to disable reallocation with -fno-realloc-lhs for performance, so for portable code do not depend on a particular mix in hot loops.

Python Stand-in (Python): growing and shrinking by assignment

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.

Copying and sizing with source and mold

allocate can copy shape and values from another array:

FORTRAN
allocate(b, source=a)      ! same shape and values as a
allocate(c, mold=a)        ! same shape and type, values undefined

Or you can allocate a matrix from sizes read at run time:

FORTRAN
read *, nrows, ncols
allocate(grid(nrows, ncols))
grid = 0.0

Allocatable in procedures

An allocatable can be a dummy argument, so a procedure can create or resize the caller's array. The most common use is returning a result whose size depends on the input:

FORTRAN
function evens(n) result(r)
  integer, intent(in) :: n
  integer, allocatable :: r(:)
  integer :: i
  r = [(2 * i, i = 1, n)]
end function evens

The function result r is allocated automatically by the assignment. For procedures that only need to use an array of any size, use an assumed-shape dummy real, intent(in) :: a(:), which works with both fixed and allocatable arguments, and is covered in the next chapter.

Automatic arrays

A local array whose size comes from a dummy argument is an automatic array, created on entry to the procedure and destroyed on exit, with no allocate:

FORTRAN
subroutine work(n)
  integer, intent(in) :: n
  real :: tmp(n)          ! size n, decided at each call
  tmp = 0.0
end subroutine work

Automatic arrays usually live on the stack, so very large sizes can crash the program with a stack overflow. For big temporaries, prefer an allocatable array, which lives on the heap.

move_alloc: transfer without copying

call move_alloc(from, to) moves the allocation of one array to another, leaving from unallocated. It is the efficient way to resize:

FORTRAN
real, allocatable :: a(:), tmp(:)

allocate(tmp(2 * size(a)))
tmp(1:size(a)) = a
call move_alloc(tmp, a)        ! a now has the doubled size; tmp is empty

This pattern (double the capacity, copy, move) is how growable vectors are built, and it avoids copying twice.

Python Stand-in (Python): capacity doubling with move_alloc

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.

Common mistakes

  • Using before allocating, or allocating twice without deallocate or an allocated check.
  • Assuming the old lower bound survives: after x = [..] the lower bound is 1 (unless you copy bounds with allocate(x(lbound(y,1):ubound(y,1)))).
  • Huge automatic arrays causing stack overflow.
  • Mismatched shapes in y(:) = ... when the sizes differ.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you declare an allocatable matrix of reals?

    The allocatable attribute with deferred-shape colons declares an array whose size is chosen later.
  2. 2. What does allocated(x) return?

    allocated is a logical function that is true when the array currently has storage.
  3. 3. What happens after y = [y, 4.0] for an allocatable y of size 3?

    Assignment to an allocatable array reallocates it to the shape of the right-hand side.
  4. 4. What does call move_alloc(tmp, a) do?

    move_alloc transfers the allocation without copying, leaving the source unallocated.

Summary

  • Declare real, allocatable :: x(:) and give it storage with allocate(x(n)).
  • Use allocated, stat= and errmsg= for safety; local allocatables are freed automatically.
  • Assignment allocates or reallocates, so x = [x, v] grows an array.
  • source= and mold= copy the shape of another array; move_alloc transfers storage without copying.
  • Automatic arrays are sized by a dummy argument but live on the stack; use allocatables for large data.

Next: Numeric Intrinsics and Floating-Point Behavior