Search code examples
fortran

When is array deallocating necessary?


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 deallocating them. Is there a method to determine if/how not deallocating impacts the execution time?

Thanks in advance

PS: I am not prone to do this test directly (by comparing the execution time with and without deallocation) because the program depends on random variables whose values will eventually affect the performance.


Solution

  • 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 an assignment, in two situations:

    • if the array's dimensions on the left and right sides 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 occurs 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.