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
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…