040. If allocation errors must be handled, use allocatable rather than automatic arrays in procedures#

topic: Allocation

If allocation errors must be handled, use allocatable rather than automatic arrays in procedures, and check the stat of allocate in order to handle errors.

alloc-stat.f90 | | 0 | Godbolt Compiler Explorer logo | Fortran logo#
program alloc_stat
   implicit none

   real, allocatable :: x(:)
   integer :: ierr

   ! Initial allocation
   allocate (x(5))
   print *, allocated(x)  ! Confirm

   ! Trying to allocate again will error
   allocate (x(42), stat=ierr)
   if (ierr /= 0) then
      print *, "error", ierr
   else
      print *, "it worked"
   end if

end program alloc_stat
Output1#
 T
 error        5014

From the Tweet, an example of handling this in a subroutine, considering the case of insufficient memory:

subroutine foo(x)
   implicit none

   real, intent(in) :: x(:)
   real :: y(size(x))
   ! ^ Automatic array -- program crashes if there is no memory for it
   real, allocatable :: z(:)
   integer :: ierr

   allocate (z(size(x)), stat=ierr)
   if (ierr /= 0) then  ! Handle allocation errors
      print *, "could not allocate z in foo"
      return
   end if

end subroutine foo


1

Compiled using GNU Fortran (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0 with no flags