Search code examples
fortranstorageallocatable-array

Recover storage of NON-allocatable large arrays in Fortran


The deallocate statement is used to recover storage of an allocatable array that is no more needed. What about non-allocatable arrays? Suppose (in the main and only program) there is a declaration like

INTEGER, DIMENSION(100,100) :: A

This array is used once and then no more. What if I want to make it's space free?


Solution

  • The example you gave is not an allocatable array, but a simple static array, that will exist only in the scope where it was created. The memory allocated to the static array usually is freed once the variable goes out of scope, but this depends on other situations, like if it is implicit saved, etc.

    To be an allocatable array, it must have ALLOCATABLE in its declaration. Also, you need to ALLOCATE it.

    The big point of allocatable arrays is that FORTRAN will manage the deallocation for you.

    As soon as the array goes out of scope, fortran will deallocate it for you. This way, there is no memory leaks risk with this array.

    Example adapted from http://www.fortran90.org/src/best-practices.html

    subroutine do_something
        real(dp), allocatable :: lam
        allocate(lam(5))
        ...
    end subroutine do_something
    

    At the end of the routine, the lam array will be automatically deallocated.