TExcelTAD
Home › Fortran › Fortran Allocatable Arrays

Fortran Allocatable Arrays

The arrays so far had a size fixed at compile time. Real programs often learn the size only at run time: the number of particles, grid points or lines in a file. Allocatable arrays solve this. You declare the rank (number of dimensions) but not the size, then allocate memory when you know it.

Declare, allocate, use, deallocate

fortran · try it yourself
program allocate_demo
  implicit none
  real, allocatable :: samples(:)        ! rank 1, size unknown
  integer :: n, i

  n = 6                                  ! imagine this came from input
  allocate(samples(n))
  samples = [(0.5 * i, i = 1, n)]

  print '(a, i0)', 'size: ', size(samples)
  print '(*(f5.1))', samples
  print '(a, l1)', 'allocated? ', allocated(samples)

  deallocate(samples)
  print '(a, l1)', 'allocated? ', allocated(samples)
end program allocate_demo
size: 6
  0.5  1.0  1.5  2.0  2.5  3.0
allocated? T
allocated? F
  • real, allocatable :: a(:) declares a 1-D allocatable array; a(:, :) would be 2-D.
  • allocate(a(n)) reserves memory; custom bounds work too: allocate(a(0:n)).
  • allocated(a) tells you whether the array currently has memory.
  • deallocate(a) frees it.

Unlike pointers in C, allocatable arrays cannot leak: when an allocatable local variable goes out of scope (for example, at the end of a subroutine), Fortran deallocates it automatically.

Automatic (re)allocation on assignment

Since Fortran 2003, assigning to an allocatable array automatically allocates it, or reallocates it if the shape differs. Often you never need to call allocate at all:

fortran · try it yourself
program auto_alloc
  implicit none
  integer, allocatable :: v(:)
  integer :: i

  v = [3, 1, 4]                     ! allocated with size 3
  print '(a, i0, a, *(i3))', 'size ', size(v), ':', v

  v = [v, 1, 5, 9]                  ! grows to size 6
  print '(a, i0, a, *(i3))', 'size ', size(v), ':', v

  v = pack(v, v > 2)                ! shrinks to the matching elements
  print '(a, i0, a, *(i3))', 'size ', size(v), ':', v

  v = [(i * i, i = 1, 4)]
  print '(a, i0, a, *(i3))', 'size ', size(v), ':', v
end program auto_alloc
size 3:  3  1  4
size 6:  3  1  4  1  5  9
size 4:  3  4  5  9
size 4:  1  4  9 16

v = [v, x] is the Fortran idiom for "append". Each append copies the whole array, so for many appends it's better to allocate a large enough array once (or to grow the capacity by doubling).

Note: Automatic reallocation happens for v = …, but not when you assign to a section like v(:) = … or v(1:n) = …. Those require the array to be already allocated with the right size.

Allocation errors: stat= and errmsg=

allocate fails if the array is already allocated or if memory runs out. Without extra arguments, the program stops. With stat= you can handle the failure yourself:

fortran · try it yourself
program alloc_errors
  implicit none
  real, allocatable :: buffer(:)
  integer :: ierr
  character(len=100) :: msg

  allocate(buffer(10))
  allocate(buffer(20), stat=ierr, errmsg=msg)    ! already allocated!
  if (ierr /= 0) then
    print '(a, i0)', 'allocate failed with stat = ', ierr
    print '(a)', trim(msg)
  end if

  if (allocated(buffer)) deallocate(buffer)
  allocate(buffer(20), stat=ierr)
  print '(a, i0, a, i0)', 'second try: stat = ', ierr, ', size = ', size(buffer)
end program alloc_errors
allocate failed with stat = 5014
Attempt to allocate an allocated object
second try: stat = 0, size = 20

The non-zero stat value is compiler-specific; only "zero means success" is guaranteed.

2-D allocatable arrays and source=/mold=

fortran · try it yourself
program alloc_2d
  implicit none
  real, allocatable :: grid(:, :), copy(:, :), blank(:, :)
  integer :: nx, ny, i

  nx = 3
  ny = 4
  allocate(grid(nx, ny))
  grid = 1.5

  allocate(copy, source=grid)       ! same shape AND values
  allocate(blank, mold=grid)        ! same shape, values undefined
  blank = 0.0
  copy(2, :) = 9.0

  print '(a, 2i3)', 'shape: ', shape(copy)
  do i = 1, nx
    print '(4f6.1)', copy(i, :)
  end do
  print '(a, f4.1)', 'sum of blank: ', sum(blank)
end program alloc_2d
shape:   3  4
   1.5   1.5   1.5   1.5
   9.0   9.0   9.0   9.0
   1.5   1.5   1.5   1.5
sum of blank:  0.0

move_alloc: grow without double copies

call move_alloc(from, to) transfers the memory of from to to without copying, leaving from deallocated. It's the standard way to resize an array while keeping its contents:

fortran · try it yourself
program grow_array
  implicit none
  integer, allocatable :: data(:), bigger(:)

  data = [10, 20, 30]
  allocate(bigger(2 * size(data)))
  bigger = 0
  bigger(1:size(data)) = data
  call move_alloc(bigger, data)          ! data now has the new memory

  print '(a, i0)', 'new size: ', size(data)
  print '(*(i4))', data
  print '(a, l1)', 'bigger still allocated? ', allocated(bigger)
end program grow_array
new size: 6
  10  20  30   0   0   0
bigger still allocated? F

Test yourself

What does real, allocatable :: m(:, :) declare?

  1. A 2-element array
  2. A 2-D array whose size is decided at run time
  3. A pointer to a real
  4. A fixed 1×1 matrix

After v = [1, 2] and then v = [v, 3] (with v allocatable), what is size(v)?

  1. 2
  2. 3
  3. An error: v was not allocated
  4. 1

What happens to a local allocatable array when its subroutine returns?

  1. It leaks memory
  2. It is deallocated automatically
  3. It keeps its value for the next call
  4. The program crashes