Allocatable arrays
An array with a size the program learns while it runs is an allocatable array: the declaration names the rank and leaves the bounds out, allocate fixes them, and the memory is given back by deallocate or by the end of the scope. This lesson allocates, deallocates, grows a vector one element at a time, and handles the failure of an allocation without stopping the program.
ALLOCATE and DEALLOCATE
The declaration integer, allocatable :: a(:) has a rank of one and no bounds. Until an allocate statement runs, the array has no elements and allocated(a) is false; a program asks that question before it asks for the size, because the size of an unallocated array is not a defined number.
The file alloc.f90:
program alloc_demo
implicit none
integer, parameter :: n = 5
integer, allocatable :: a(:)
integer :: i
allocate(a(n))
a = [(i * 10, i = 1, n)]
print *, "allocated :", allocated(a)
print *, "size :", size(a)
print *, "bounds :", lbound(a), ubound(a)
print *, "a :", a
deallocate(a)
print *, "allocated :", allocated(a)
end program alloc_demo
gfortran -Wall -Wextra -std=f2018 alloc.f90 -o alloc
./alloc
allocated : T
size : 5
bounds : 1 5
a : 10 20 30 40 50
allocated : F
allocate(a(n)) gives the array the bounds 1 to n, which is the same lower bound a fixed-size array has. A different lower bound is allowed: allocate(a(0:n-1)) makes the array start at zero, and every later lbound, section and loop has to agree with that choice.
Allocation on assignment
Since Fortran 2003 an assignment to an allocatable array allocates it, or reallocates it when the shape differs. The array takes the shape of the right side, which makes a program that collects values read like a sequence of values rather than a sequence of allocations.
The file auto.f90:
program auto_demo
implicit none
integer, allocatable :: a(:)
a = [1, 2, 3]
print *, "size :", size(a), " a :", a
a = [10, 20, 30, 40]
print *, "size :", size(a), " a :", a
a = [7]
print *, "size :", size(a), " a :", a
end program auto_demo
gfortran -Wall -Wextra -std=f2018 auto.f90 -o auto
./auto
size : 3 a : 1 2 3
size : 4 a : 10 20 30 40
size : 1 a : 7
The first assignment allocates three elements, the second reallocates four and drops the old storage, the third shrinks the array to one. Nothing was declared with a size and nothing was deallocated by hand: the array follows its value. A list-directed print puts the label, the size and the array on one line, each item separated by the space the list format inserts.
Growing an array
An array cannot be extended in place. To add an element a program allocates a new array of the larger size, copies the old values, and moves the new array into the old name with move_alloc, which also deallocates the old target. The copy is the cost, and a program that grows in a loop doubles the capacity rather than adding one element at a time.
The file grow.f90 grows by one element per step so that every intermediate size is visible:
program grow_demo
implicit none
integer, allocatable :: v(:), bigger(:)
integer :: i, n
n = 0
allocate(v(0))
do i = 1, 6
allocate(bigger(n + 1))
bigger(1:n) = v
bigger(n + 1) = i * i
call move_alloc(bigger, v)
n = n + 1
print *, "n =", n, "size =", size(v), "v =", v
end do
end program grow_demo
gfortran -Wall -Wextra -std=f2018 grow.f90 -o grow
./grow
n = 1 size = 1 v = 1
n = 2 size = 2 v = 1 4
n = 3 size = 3 v = 1 4 9
n = 4 size = 4 v = 1 4 9 16
n = 5 size = 5 v = 1 4 9 16 25
n = 6 size = 6 v = 1 4 9 16 25 36
bigger(1:n) = v with n = 0 is a zero-sized section assigned from a zero-sized array, which is legal and copies nothing. After move_alloc the source bigger is unallocated again, so the next pass can allocate it without a deallocate.
STAT and ERRMSG
An allocation can fail, and a program that allocates from a size it read from a file should not die on a bad number. The keywords stat and errmsg turn the failure into a value: zero means success and a positive number is the error, with a message in the character variable.
The file stat.f90 allocates the same array twice and prints what the second attempt reports:
program stat_demo
implicit none
integer, allocatable :: a(:)
integer :: stat
character(len=200) :: msg
msg = ""
allocate(a(3), stat=stat, errmsg=msg)
print *, "first :", stat, trim(msg)
allocate(a(4), stat=stat, errmsg=msg)
print *, "second :", stat, trim(msg)
print *, "size :", size(a)
end program stat_demo
gfortran -Wall -Wextra -std=f2018 stat.f90 -o stat
./stat
first : 0
second : 5014 Attempt to allocate an allocated object
size : 3
The status is a number the language does not fix, so a program tests it against zero and never against 5014: that value is what this gfortran happened to report, and another compiler or another error has another one. The message is worth printing as it comes.
Note the msg = "" before the first call. On success the standard does not define the message variable, so a program that prints it without initialising it prints whatever the variable held; the initialisation is what makes the first line of the output empty.
Lifetime and scope
An allocatable local of a procedure, or of a block, is deallocated automatically when the scope ends, so a procedure that allocates and returns leaks nothing even without a deallocate. An explicit deallocate is still right when the memory is large and the rest of the procedure does other work, and it is required before an allocate of the same variable unless the shape is being changed by an assignment.
Deallocating an unallocated array is an error, and so is allocating an allocated one. The two questions a program asks before either statement are allocated(a) and size(a), and the two answers are cheap.
Exercises
- Change allocate(a(n)) to allocate(a(0:n-1)). What do lbound and ubound print, and does the assignment still work?
- Remove the deallocate(a) from alloc.f90. What does the last line print, and why is the program still correct?
- Replace the one-element growth in grow.f90 with a doubling of the capacity. How many allocations does it take for six values?
- Print size(a) before the first allocate. What happens, and what does the compiler say about it?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
integer, allocatable :: a(:)declare?Answer
A rank-one array whose bounds are set later
The declaration fixes the rank and leaves the bounds to ALLOCATE.
-
What does
allocated(a)return before the first ALLOCATE?Answer
.FALSE.
An allocatable that has not been allocated holds no elements.
-
What does this program print?
program p implicit none integer, allocatable :: a(:) a = [1, 2, 3] a = [4, 5] print *, size(a) end program pAnswer
2
Assignment reallocates to the shape of the right side, which has two elements.
-
What does
move_alloc(bigger, v)do?Answer
Moves the storage of bigger into v and deallocates bigger
The move transfers the allocation and leaves the source unallocated.
-
What does a nonzero STAT from ALLOCATE mean?
Answer
The allocation failed and the program continues
STAT turns the failure into a value instead of a crash.
-
Why does
stat.f90setmsg = ""before the first allocate?Answer
On success ERRMSG is not defined, so the variable would print stale contents
The standard defines the message only when the status is nonzero.
-
When is a local allocatable of a procedure deallocated?
Answer
Automatically when the procedure or block ends
The scope owns the allocation and releases it at the end.
-
What happens if a program allocates an array that is already allocated, with no STAT?
Answer
The program stops with a runtime error
A second ALLOCATE of the same variable is an error at run time.
-
Which statement changes the shape of an allocated array without DEALLOCATE?
Answer
An assignment of a value with another shape
Allocation on assignment reallocates to the shape of the right side.
-
What do the bounds
allocate(a(0:n-1))give the array?Answer
A lower bound of 0 and an upper bound of n - 1
The two numbers in the allocation are the bounds themselves.
The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev