Allocatable components and deep copy
A record with an allocatable component owns its storage, and Fortran's assignment is a copy of everything: the scalar components one by one and the allocatable ones allocated fresh and filled. That rule is what makes a record behave like a value and what makes a large one expensive to pass around. This lesson measures the two halves of the rule, deallocates through intent(out), moves storage instead of copying it, and grows a list of records without leaking the old one.
Assignment is a copy
b = a for two records with an allocatable component allocates b%data at the size of a%data and copies element by element. The two records then own two separate arrays: writing into one is invisible in the other. The program below shows that, and then what a call with intent(out) does to the value the caller passes.
The file deep.f90:
module series_mod
implicit none
private
public :: series, make_series, reset
type :: series
character(len=8) :: name = 'series'
real, allocatable :: data(:)
end type series
contains
function make_series(name, n) result(s)
character(len=*), intent(in) :: name
integer, intent(in) :: n
type(series) :: s
integer :: i
s%name = name
allocate(s%data(n))
do i = 1, n
s%data(i) = real(i)
end do
end function make_series
subroutine reset(s)
type(series), intent(out) :: s
print '(a,l1)', 'inside reset: allocated = ', allocated(s%data)
s%name = 'reset'
allocate(s%data(1))
s%data = 0.0
end subroutine reset
end module series_mod
program deepdemo
use series_mod
implicit none
type(series) :: a, b
real, allocatable :: moved(:)
a = make_series('a', 3)
print '(a,3f5.1)', 'a%data =', a%data
b = a
b%data(1) = 99.0
print '(a,3f5.1)', 'a%data =', a%data
print '(a,3f5.1)', 'b%data =', b%data
call reset(b)
print '(a,a,a,3f5.1)', 'b after reset = ', trim(b%name), ' ', b%data
print '(a,3f5.1)', 'a still =', a%data
call move_alloc(a%data, moved)
print '(a,l1)', 'a%data allocated after move = ', allocated(a%data)
print '(a,3f5.1)', 'moved =', moved
end program deepdemo
gfortran -Wall -Wextra -std=f2018 deep.f90 -o deep
./deep
a%data = 1.0 2.0 3.0
a%data = 1.0 2.0 3.0
b%data = 99.0 2.0 3.0
inside reset: allocated = F
b after reset = reset 0.0
a still = 1.0 2.0 3.0
a%data allocated after move = F
moved = 1.0 2.0 3.0
The first two lines are the deep copy: b%data(1) = 99.0 changed one array and the other still starts with one. The third line is the important one for a reader who knows C: there is no pointer here to share a buffer, so a record passed to a procedure is a record of its own, and copying one is a real cost.
INTENT(OUT) and the old value
A dummy with intent(out) is undefined when the procedure starts, and the language enforces that by deallocating its allocatable components on entry. The line printed from inside reset is F: the three elements that b had are gone before the first assignment. The subroutine then allocates one element, and the caller sees a record with one element.
An intent(inout) dummy keeps the value, and an intent(in) dummy may not write it. So the three intents are three different promises about the storage, not only about the components, and a procedure that wants to add to a series takes it as intent(inout).
MOVE_ALLOC
call move_alloc(a%data, moved) transfers the allocation: after the call moved owns the storage and a%data is unallocated, which is the F on the last lines. No element is copied, so the cost is a few words of bookkeeping whatever the size of the array.
That is the tool for a function that builds a big array and returns it: allocate a local, fill it, and let move_alloc hand it to the caller instead of letting the assignment copy it. It is also how a container grows without copying the old buffer twice, which is the next section.
A growing list
A list of records with allocatable components is an allocatable array of them, and appending means a new array of one more element. tmp(1:size(list)) = list copies every element, each one a deep copy of its component; move_alloc then installs the new array without copying it again.
The file grow.f90:
program growdemo
implicit none
type :: item
integer :: id = 0
real, allocatable :: v(:)
end type item
type(item), allocatable :: list(:)
integer :: i
allocate(list(0))
call append(list, 10, 1.0)
call append(list, 20, 2.0)
call append(list, 30, 3.0)
print '(a,i0)', 'size = ', size(list)
do i = 1, size(list)
print '(a,i0,a,2f6.1,a,f7.2)', 'item ', list(i)%id, ' v =', list(i)%v, ' sum = ', sum(list(i)%v)
end do
contains
subroutine append(list, id, x)
type(item), allocatable, intent(inout) :: list(:)
integer, intent(in) :: id
real, intent(in) :: x
type(item), allocatable :: tmp(:)
allocate(tmp(size(list) + 1))
tmp(1:size(list)) = list
tmp(size(list) + 1)%id = id
tmp(size(list) + 1)%v = [x, 2.0 * x]
call move_alloc(tmp, list)
end subroutine append
end program growdemo
gfortran -Wall -Wextra -std=f2018 grow.f90 -o grow
./grow
size = 3
item 10 v = 1.0 2.0 sum = 3.00
item 20 v = 2.0 4.0 sum = 6.00
item 30 v = 3.0 6.0 sum = 9.00
Three appends, three sizes, and the old arrays were deallocated by the assignment to tmp and by move_alloc. The cost is the copy of every element at every append: for n appends the work is proportional to n^2 in the number of elements, which matters at a few thousand and does not at a few dozen. A container that grows by doubling the capacity and keeping a count of the used part is the standard answer, and it is a derived type with two components.
What the copy costs
Two habits keep the copies away without changing the design. Pass a record that is only read as intent(in): the dummy is then not copied at all, since a read-only dummy may be the caller's own record. And return a big value through move_alloc rather than = where the language allows it, which is any point where the source is about to die.
The copies that remain are real work and not a defect: b = a has to produce two independent records, and there is no way to do that without touching the elements. What a program can do is stop writing the copy it does not need, which is what an intent(in) dummy and a move_alloc are for.
A component of an INTENT(IN) dummy
Writing into a component of a read-only dummy is refused, and the message names the dummy and the context:
program badintent
implicit none
type :: series
character(len=8) :: name = 'series'
real, allocatable :: data(:)
end type series
type(series) :: a
allocate(a%data(3))
call wipe(a)
print *, a%data
contains
subroutine wipe(s)
type(series), intent(in) :: s
s%data = 0.0
end subroutine wipe
end program badintent
gfortran -Wall -Wextra -std=f2018 badintent.f90 -o badintent
badintent.f90:18:5:
18 | s%data = 0.0
| 1~~~~~
Error: Dummy argument 's' with INTENT(IN) in variable definition context (assignment) at (1)
The phrase "variable definition context" is the standard's term for anywhere a value may be written, and it covers a component, an element and an allocatable's allocation status. The fix is intent(inout) if the procedure really changes the value, and a local copy if it only wants to look at a modified version.
Ownership in Fortran
Three declarations own storage and three do not. An allocatable owns it and frees it when it goes out of scope, a pointer does not own it and may dangle, and a component of either kind follows its record. Assignment copies an allocatable, which is a deep copy of the component; pointer assignment aliases, which is the subject of part 8. Mixing the two in one design is where most memory bugs in Fortran come from.
The rule of thumb of this course: an allocatable unless there is a reason, and a reason means one of three things, a data structure that needs a cycle, an array section passed to a routine that cannot take an assumed shape, and a C pointer that has to be stored. Nothing else needs a pointer, and an allocatable cannot dangle.
Exercises
- Change reset to intent(inout) and run the program. Which two lines of the output change?
- Add an append that puts the new element first instead of last. Which line of the copy changes?
- Replace call move_alloc(a%data, moved) with moved = a%data and print allocated(a%data) afterwards. What is different?
- Declare type(series), pointer :: p and point it at a. Does p%data(1) = 42.0 change a%data(1)?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
b = ado when both records have an allocatable component?Answer
Allocates b%data anew and copies every element
Assignment of an allocatable is a deep copy.
-
What is the state of an allocatable component of an INTENT(OUT) dummy on entry?
Answer
Deallocated: the old value is gone
INTENT(OUT) means the dummy starts undefined.
-
What does MOVE_ALLOC do?
Answer
Transfers the allocation without copying elements
The source ends unallocated and the target owns the storage.
-
What does this program print?
program p implicit none type :: t integer, allocatable :: v(:) end type t type(t) :: a, b allocate(a%v(2)) a%v = [1, 2] b = a b%v(1) = 9 print *, a%v(1), b%v(1) end program pAnswer
1 9
The two records own separate arrays after the copy.
-
How does a list of records grow by one element?
Answer
Allocate a longer array, copy the elements, MOVE_ALLOC it in
Fortran arrays have a fixed size once allocated.
-
What does writing into a component of an INTENT(IN) dummy give?
Answer
Error: dummy argument in variable definition context
INTENT(IN) forbids every write, component included.
-
Which declaration owns its storage?
Answer
An allocatable
An allocatable frees its storage with the scope.
-
Why does an INTENT(IN) dummy avoid a copy?
Answer
A read-only dummy may be the caller's own record
Nothing can change it, so the compiler passes the address.
-
What is the cost of appending n elements one at a time to an allocatable array?
Answer
Proportional to n squared, because every element is copied at every append
Each append rebuilds the whole array.
-
When is a pointer justified over an allocatable?
Answer
For a cycle, a section for an old routine, or a stored C pointer
An allocatable cannot dangle and is the safer default.
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