2

If I define the following subroutine in Fortran

SUBROUTINE (A)
REAL :: A(:,:)
REAL :: B(SIZE(A,1),SIZE(A,2))
...

The matrix B is automatically deallocated at the end of the subroutine?

In that sense, is better to write a subroutine as the last, or it is better to define something like the following?

SUBROUTINE (A)
REAL :: A(:,:)
REAL, ALLOCATABLE :: B(:,:)

ALLOCATE(B(SIZE(A,1),SIZE(A,2)))

...

DEALLOCATE(B)
...
user106306
  • 315
  • 2
  • 10
  • 5
    Yes. All allocatable arrays are automatically deallocated when they go out of scope. There is no need to deallocate at the end of the subroutine, allocatables can never leak memory. No time to look for a duplicate but there must be one somewhere. – Ian Bush Mar 24 '21 at 14:23
  • 1
    N.B. "allocatables can never leak memory" is true by the standard, but may not be true by current compiler implementations; there are a number of extant memory-leak bugs, e.g. [this gfortran bug](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=93624) – veryreverie Mar 24 '21 at 14:32
  • Does this answer your question? [When is array deallocating necessary?](https://stackoverflow.com/questions/50634582/when-is-array-deallocating-necessary) – veryreverie Mar 24 '21 at 14:37
  • 2
    `B` isn't an allocatable array in the first example but an automatic one. – francescalus Mar 24 '21 at 14:42
  • 1
    Whoops. But in both cases the array will be allocated when it goes out of scope, modulo compiler bugs. I prefer the second as you are less likely to run into problems due to trying to use to much of the stack, and there is some hope that you can actually detect an allocation failure at run time, though most OS's in practice make this latter point a vain hope. – Ian Bush Mar 24 '21 at 14:55

0 Answers0