7
$\begingroup$

I understand the crucial importance of freeing memory when certain variables or arrays need to be reused later in the program, or may not be in use for a while. However, in my experience with scientific computing a lot of the code written is meant to be run as a job and produce results, rather than the case of conventional software (a web browser for instance) which is listening for user input not knowing how much memory may be required.

So if certain arrays and variables are used throughout the entire program is there any point to dedicating a section of the program before exiting that will deallocate the memory used? My understanding is the operating system will take all memory back from a terminated program anyways.

Looking forward to any thoughts and opinions on the subject.

$\endgroup$
9
$\begingroup$

Fortran's allocatable variables are automatically deallocated when the variable goes out of scope (see http://www.fortran90.org/src/best-practices.html#allocatable-arrays). This means that it is not possible to create a memory leak by failing to deallocate an allocatable array. This is one of the big benefits of using allocatable arrays rather than pointers.

Additionally, allocating and deallocating memory takes time so it is not advisable to repeatedly allocate and deallocate an array unless there is a good reason to do so.

Finally, as you mentioned, the operating system will re-claim all memory used by the program once the program terminates. This is true regardless of how the memory was allocated. In the case you mentioned (allocatable arrays that are used for the entire life of the program), deallocating before exit may be seen as more of a bookkeeping step than a necessity. It is a form of self-documentation and also makes users of the code aware of the existence of still-allocated arrays. This could be important if the code were to be later modified or incorporated into a larger program.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.