1

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?

Enlico
  • 23,259
  • 6
  • 48
  • 102
  • What if I want to make it's space free? Use an allocatable array. – Vladimir F Героям слава Jun 30 '16 at 11:53
  • Maybe I'm wrong but I use allocatable arrays when I don't know _a priori_ how many elements the array is going to be made up of. There are cases where the array has a known dimension by definition (e.g. the inertia tensor is a 3 by 3 matrix). So are you saying that even in this cases the solution is to make them allocatable, allocate them and then deallocate? – Enlico Jun 30 '16 at 12:21
  • 2
    Allocatables (and pointers) do dynamic association/memory management. Yes, they are useful in this regard even when an explicit size is possible. – francescalus Jun 30 '16 at 12:31
  • [Another question](https://stackoverflow.com/q/31433121) may be of some interest. [Not duplicate.] – francescalus Jun 30 '16 at 12:56
  • @francescalus, if your first comment means that there's no way to free the space of a non-allocatable array in the main program, then you could write an answer. – Enlico Jul 01 '16 at 06:38

1 Answers1

1

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.

Jauch
  • 1,500
  • 9
  • 19
  • 3
    *"the memory will be freed after the execution goes out of its scope"* Depends where it is placed. If it is implicitly saved (located in the main program or a module) it will not be deallocated. If it is in a subroutine, it may be placed on the stack or it may be static or it may be allocated on the heap and it also changes the behaviour. – Vladimir F Героям слава Jun 30 '16 at 11:54
  • You're completely right. I updated the answer to take your observations into account. – Jauch Jul 01 '16 at 10:57