Fortran allocatable array lifetime

2019-03-05 12:03发布

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?

1条回答
不美不萌又怎样
2楼-- · 2019-03-05 12:44

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.

查看更多
登录 后发表回答