Deallocation, leaks and finalisation

Fortran has no garbage collector, but it has three release paths that do most of the work without a line of code: an allocatable frees itself at the end of its scope, an allocatable component goes with its record, and a deallocate is explicit only when the program wants the memory back early. What it does not have is a release path for a pointer, and this lesson shows the leak that a forgotten one leaves, with valgrind naming the line.

DEALLOCATE

deallocate(a) returns the storage of an allocatable or frees what a pointer allocation took. After it the variable is unallocated, allocated(a) is false, and the next allocate may give it any shape. Doing it twice is an error the runtime reports, which is the subject of a later section.

Explicit deallocation is worth writing when the amount of memory is large and the scope is long: a program that reads one big array, processes it and reads the next one should free the first before the second arrives. In a short procedure the automatic release at the end of the scope is enough, and code that deallocates everything by hand is harder to read than the same code without those lines.

Automatic deallocation

The program below has two builders that do the same thing to a million reals; one keeps the array in a pointer and one in an allocatable. Both print a sum and both return. Then the whole program is run under valgrind, which counts what is still allocated when the process exits.

The file leak.f90:

program leakdemo implicit none call make_pointer() call make_allocatable() print *, 'both builders returned' contains subroutine make_pointer() real, pointer :: p(:) allocate(p(1000000)) p = 1.0 print '(a,f10.1)', 'pointer sum = ', sum(p) end subroutine make_pointer subroutine make_allocatable() real, allocatable :: a(:) allocate(a(1000000)) a = 2.0 print '(a,f10.1)', 'allocatable sum = ', sum(a) end subroutine make_allocatable end program leakdemo

gfortran -Wall -Wextra -std=f2018 -g leak.f90 -o leak
./leak

pointer sum = 1000000.0
allocatable sum = 2000000.0
 both builders returned

The program looks correct and prints correct numbers: both sums are what a million values of one and of two add up to. The pointer builder returned without freeing its array, and the allocatable builder returned with the array freed for it. Nothing in the output says so, which is why the next command exists.

A leak, and valgrind

valgrind is in this image, so the run below is real. It is the same binary, built with -g so that the leak report can name a source line.

valgrind --leak-check=full ./leak

==491== Memcheck, a memory error detector
==491== Copyright (C) 2002-2024, and GNU GPL'd, by Julian Seward et al.
==491== Using Valgrind-3.25.1 and LibVEX; rerun with -h for copyright info
==491== Command: ./leak
==491==
pointer sum = 1000000.0
allocatable sum = 2000000.0
 both builders returned
==491==
==491== HEAP SUMMARY:
==491== in use at exit: 4,000,000 bytes in 1 blocks
==491== total heap usage: 23 allocs, 22 frees, 8,010,654 bytes allocated
==491==
==491== 4,000,000 bytes in 1 blocks are definitely lost in loss record 1 of 1
==491== at 0x48B7733: malloc (vg_replace_malloc.c:446)
==491== by 0x4001653: make_pointer.1 (leak.f90:11)
==491== by 0x4001514: MAIN__ (leak.f90:4)
==491== by 0x400185D: main (leak.f90:6)
==491==
==491== LEAK SUMMARY:
==491== definitely lost: 4,000,000 bytes in 1 blocks
==491== indirectly lost: 0 bytes in 0 blocks
==491== possibly lost: 0 bytes in 0 blocks
==491== still reachable: 0 bytes in 0 blocks
==491== suppressed: 0 bytes in 0 blocks
==491==
==491== For lists of detected and suppressed errors, rerun with: -s
==491== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

Reading the valgrind output

The number between the equals signs is the id of the valgrind process, so it changes with every run; everything else in the report is stable for the same binary. The program's own output appears where it happened, between the start-up lines and the summary.

in use at exit: 4,000,000 bytes in 1 blocks is the memory the process still held when it returned: exactly the million single-precision reals of the pointer builder, four bytes each. The allocatable array is not in it, because its scope ended before the program did. The loss record then names the allocation: make_pointer.1 (leak.f90:11) is the allocate line, called from line 4, called from the main program.

Two numbers in the summary are worth knowing. definitely lost means no pointer to the block survives, so it can never be freed: that is the leak. still reachable means a pointer to it does survive, which for a long-running program is a leak as well and for a program about to exit is harmless. A clean run says All heap blocks were freed -- no leaks are possible.

The fix is one line in make_pointer: deallocate(p) before the subroutine ends, or a pointer that is an allocatable instead, which would have freed itself. The next run reports no leaks, and that is the check to keep in a test script rather than in a habit.

A double deallocation

A second deallocate of the same variable is a runtime error, and the runtime stops the program rather than corrupting the allocator:

program twicedemo implicit none real, allocatable :: a(:) allocate(a(3)) a = 1.0 print '(a,f5.1)', 'sum = ', sum(a) deallocate(a) print '(a)', 'deallocated once' deallocate(a) print '(a)', 'this line never runs' end program twicedemo

gfortran -Wall -Wextra -std=f2018 twice.f90 -o twice

GFORTRAN_ERROR_BACKTRACE=0 ./twice

sum = 3.0
deallocated once
At line 10 of file twice.f90
Fortran runtime error: Attempt to DEALLOCATE unallocated 'a'

The run stops with exit status 2, and the message names the line and the variable. The environment variable only suppresses the backtrace of addresses that would otherwise follow; without it the same two lines come first and then a list of frames that means nothing without a debugger.

Set the variable to zero in a script that checks the message, and leave the backtrace on when a person is debugging. A program that reaches this error has one path that deallocates twice, and the fix is allocated(a) in front of the second one or, better, one owner for the storage.

A non-allocatable

Deallocating a variable that was never allocated is caught at compile time when the declaration is in sight:

program baddealloc implicit none real :: x x = 1.0 deallocate(x) print *, x end program baddealloc

gfortran -Wall -Wextra -std=f2018 baddealloc.f90 -o baddealloc

baddealloc.f90:6:15:

6 | deallocate(x)
| 1
Error: Allocate-object at (1) is not a nonprocedure pointer nor an allocatable variable

The wording covers both allowed cases and refuses everything else: an allocate-object is an allocatable or a pointer. A plain real has no allocation status, so there is nothing to release, and the compiler says so before the program exists.

Rules for memory

Four rules cover this part of the course. Store in allocatables, so that the release is automatic. Give every pointer an owner with a rule about when the target dies, and nullify the pointer when it does. Deallocate early only where the memory matters, and never twice. And run the program under valgrind once after a change to the allocation logic, because a leak is invisible in every other kind of test.

For a finaliser that closes a resource rather than memory, section 081 has the details and the two places where this build does not run it. Memory that Fortran allocates for an allocatable never needs a finaliser: the release path is in the language, and the only thing a program has to get right is which declaration owns what.

Exercises

  1. Add deallocate(p) to make_pointer and run valgrind again. Which line of the summary changes?
  2. Change the pointer in make_pointer to an allocatable and run valgrind. Why is the report clean without a deallocate?
  3. Put the second deallocate behind if (allocated(a)). Does the message disappear, and what does the program print instead?
  4. Allocate a pointer in the main program, pass it to a subroutine that nullifies it, and run valgrind. Is the block reported as definitely lost or still reachable?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What happens at the end of the scope of an allocatable local?

    Answer

    It is deallocated automatically

    The allocation status belongs to the variable.

  2. Why does an array held in a pointer and never deallocated leak?

    Answer

    A pointer does not own its storage and nothing frees it

    Only an explicit DEALLOCATE or a finaliser would free it.

  3. What does this program print? program p implicit none real, allocatable :: a(:) allocate(a(2)) a = [1.0, 2.0] print *, allocated(a) deallocate(a) print *, allocated(a) end program p

    Answer

    T then F

    allocated answers the allocation status.

  4. What does definitely lost mean in a valgrind report?

    Answer

    No pointer to the block survives, so it can never be freed

    That is the leak valgrind proves.

  5. What does valgrind need to name a source line in its report?

    Answer

    The program built with -g

    Debug information is what maps an address to a line.

  6. What does a second DEALLOCATE of the same variable do?

    Answer

    Stops the program with "Attempt to DEALLOCATE unallocated"

    The runtime checks and terminates with status 2.

  7. What does GFORTRAN_ERROR_BACKTRACE=0 change?

    Answer

    It suppresses the list of frames after a runtime error

    The message and the exit status stay the same.

  8. What does gfortran report for deallocate(x) on a plain real?

    Answer

    Error: allocate-object is not a nonprocedure pointer nor an allocatable variable

    A plain variable has no allocation status.

  9. Which declaration needs no explicit release line?

    Answer

    An allocatable component of a record

    It is freed with its record, which is freed with its scope.

  10. When is a valgrind run worth the time?

    Answer

    After a change to the allocation logic, since leaks are invisible otherwise

    A leak changes no output and no exit status.

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