Section Arrays: Double Deallocate#
Adapted from: gjbex/Fortran-MOOC
This program demonstrates double deallocation of an array.#
From ChatGPT 4o:
The given Fortran program performs a series of operations to allocate, deallocate, and print an array. Let’s break it down step by step:
Code Analysis#
Declarations and Parameters:
nr_values = 5
: Defines the number of elements in the array.values
: An allocatable integer array that will be dynamically allocated later.i
: An integer loop variable.
Allocation:
allocate(values(nr_values), source=[ (i, i=1, nr_values) ])
This line allocates an array
values
of size 5 and initializes its elements with a sequence of integers from 1 to 5 using the implied-do loop(i, i=1, nr_values)
.
Printing the Array:
print *, values
This prints the contents of the
values
array to the console. The expected output is:1 2 3 4 5
Deallocate:
deallocate (values)
This frees the memory allocated for the
values
array.
Double Deallocate:
deallocate (values)
This attempts to deallocate the
values
array a second time, which is already deallocated.
Behavior of the Code#
The first deallocation is valid and correctly releases the memory.
The second deallocation of the
values
array will likely lead to a runtime error because the arrayvalues
is no longer allocated after the firstdeallocate
statement. Accessing or deallocating an unallocated array is an invalid operation in Fortran.
Expected Outcome#
When you run this program:
The array will be printed correctly.
The first
deallocate
will work as expected.The second
deallocate
will cause a runtime error such as:Attempting to DEALLOCATE an unallocated variable.
Key Notes#
Always check the allocation status of allocatable variables using the
allocated
intrinsic before deallocating:if (allocated(values)) deallocate(values)
This ensures that the program does not attempt to deallocate an unallocated variable, preventing runtime errors.
Program Code#
program double_deallocate
implicit none
integer, parameter :: nr_values = 5
integer, dimension(:), allocatable :: values
integer :: i
allocate(values(nr_values), source=[ (i, i=1, nr_values) ])
print *, values
deallocate (values)
deallocate (values)
end program double_deallocate
The above program is compiled and run using Fortran Package Manager (fpm):
Build the Program using FPM (Fortran Package Manager)#
import os
root_dir = ""
root_dir = os.getcwd()
The following FPM configuration file (fpm.toml) was used:
name = "Section_Arrays_Double_Deallocate"
[build]
auto-executables = true
auto-tests = true
auto-examples = true
[install]
library = false
[[executable]]
name="Section_Arrays_Double_Deallocate"
source-dir="app"
main="section_arrays_double_deallocate.f90"
code_dir = root_dir + "/" + "Fortran_Code/Section_Arrays_Double_Deallocate"
os.chdir(code_dir)
build_status = os.system("fpm build 2>/dev/null")
Run the Program using FPM (Fortran Package Manager)#
exec_status = \
os.system("fpm run")
1 2 3 4 5