I have read that applying DEALLOCATE
to an allocated array frees the space it was using. I deal with several allocatable arrays in my program, but never bother
Can deallocating variables no longer needed affect execution speed? Yes. Is it likely to in "normal" programs? No, if not preventing memory leaks.
There is no valuable heuristic of which I'm aware to help you determine usefulness of deallocating "for speed".
As previously mentioned, deallocating may be necessary for correctness or avoiding memory leaks.
However, if a program requires finalization of an allocatable variable for correctness then it will be necessary to have a deallocate
statement for it: finalization does not occur when termination of execution comes about by a stop or end program statement.
Allocatable variables declared within a procedure (subroutine or function) without the save
attribute (so-called unsaved local variables) are deallocated automatically when the procedure ends execution.
As a historical note, though, this wasn't true in Fortran 90. In Fortran 90 such variables were not deallocated and worse was that the allocation status of them became undefined (so that even the allocation status couldn't be queried). One really wanted a deallocate
there. This deficiency was corrected in Fortran 95 but habits and code may live for a long time.
Indeed, deallocation frees the memory occupied by the variables, but not always you need to do it manually.
If you know you won't need the content of the variable anymore AND you need to free up memory for other variables to be allocated (or for the system), you can use the deallocate
statement.
However, deallocation occurs automatically when the variable goes out of scope (Fortran 95 or later, as pointed by @francescalus) or when you reach the end of the program.
Also, deallocation occurs automatically, when necessary, before assignment, if array's dimensions don't coincide or if the variable is polymorphic and have to assume a conformable dynamic type. (This behavior is Fortran2003 or later, and may need to be turned ON on some compilers).
Moreover, when an allocated object is argument-associated with a dummy argument that has the attribute INTENT(OUT)
, deallocation occur before entering the procedure.
** Warning for Pointer variables:**
If you allocated storage for a pointer
variable explicitly (with the allocate
statement), and after that you perform a pointer association ( =>
), deallocation DOES NOT occur automatically. You are responsible for deallocating the variable before doing it or else memory leaks will happen.
As a final note, trying to deallocate a variable that is not allocated throws an error. You can check if an allocatable variable is allocated with the intrinsic function allocated
.