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
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_demosize: 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:
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_allocsize 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 likev(:) = …orv(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:
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_errorsallocate 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=
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_2dshape: 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:
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_arraynew size: 6
10 20 30 0 0 0
bigger still allocated? F
Test yourself
What does real, allocatable :: m(:, :) declare?
- A 2-element array
- A 2-D array whose size is decided at run time
- A pointer to a real
- A fixed 1×1 matrix
After v = [1, 2] and then v = [v, 3] (with v allocatable), what is size(v)?
- 2
- 3
- An error: v was not allocated
- 1
What happens to a local allocatable array when its subroutine returns?
- It leaks memory
- It is deallocated automatically
- It keeps its value for the next call
- The program crashes