Start with the allocator subroutine alloc. For the key functionality to work, our subroutine needs to do the following:
- Check if the input array is already allocated and, if yes, deallocate it before proceeding.
- Allocate the array with input size
n. - If an exception occurs during allocation, abort the program and print the error message to screen.
The following listing demonstrates the implementation.
Listing 5.16 Allocating an array with error handling
subroutine alloc(a, n)
real, allocatable, intent(in out) :: a(:) ❶
integer, intent(in) :: n ❷
integer :: stat ❸
character(100) :: errmsg ❹
if (allocated(a)) call free(a) ❺
allocate(a(n), stat=stat, errmsg=errmsg) ❻
if (stat > 0) error stop errmsg ❼
end subroutine alloc
❹ Character string to store the error message
❻ Allocates with error handling
❼ If nonzero status, aborts and prints error message
Now, take a look at the implementation of the free subroutine shown in the following listing.
Listing 5.17 Freeing an array with error handling
subroutine free(a)
real, allocatable, intent(in out) :: a(:) ❶
integer :: stat ❷
character(100) :: errmsg ❸
if (.not. allocated(a)) return ❹
deallocate(a, stat=stat, errmsg=errmsg) ❺
if (stat > 0) error stop errmsg ❻
end subroutine free
❸ Character string to store the error message
❺ Deallocates with error handling
❻ If nonzero status, aborts and prints error message
The code is very similar to alloc except that here, at the start of the executable section of the code, we check if a is already allocated. If not, our job here is done, and we can return immediately.
These subroutines are also part of the stock-prices repository. You can find them in src/mod_alloc.f 90, and they are used by the CSV reader in src/mod_io.f 90.