Fortran

Guide To Learn

Exercise 1: Convenience (de)allocator subroutines

Start with the allocator subroutine alloc. For the key functionality to work, our subroutine needs to do the following:

  1. Check if the input array is already allocated and, if yes, deallocate it before proceeding.
  2. Allocate the array with input size n.
  3. 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

❶ Array to allocate

❷ Array size

❸ Integer status code

❹ Character string to store the error message

❺ Free if already allocated

❻ 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

❶ Array to deallocate

❷ Integer status code

❸ Character string to store the error message

❹ If already freed, return

❺ 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.

Exercise 1: Convenience (de)allocator subroutines

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top