Search code examples
memory-managementfortranfortran90dynamic-memory-allocationfortran95

Fortran allocatable array lifetime


Say I have the below code:

program test
  call foo
  call foo
contains
  subroutine foo
    integer(8),dimension(:),allocatable:: var1
    allocate(var1(10))
    ...
    return
  end subroutine foo
end

will the variable var1 get allocated twice? (I guess YES). If it is allocated for each call, will the memory allocated during the first call becomes free?


Solution

  • var1 will (attempt to) be allocated every time the ALLOCATE statement is executed (i.e. every time the foo procedure is called).

    Under the rules of Fortran 90 (only) the allocation status of foo becomes undefined when the procedure ends. A variable with undefined allocation status is rendered unusable - you cannot legally re-allocate in a subsequent call of the procedure.

    In Fortran 95 and later, because it is a local, non-saved variable, var1 will be deallocated every time execution of the foo procedure ends.