Community
cancel
Showing results for 
Search instead for 
Did you mean: 
Highlighted
Novice
62 Views

Retention of allocated memory within a subroutine that is called multiple times

I have a question about what happens to memory allocated within a subroutine if that subroutine is called multiple times. For example, when I call it for the first time the subroutine ALLOCATEs some memory for an array, puts some data into the array and then exits (no DEALLOCATE is done). If I call the subroutine again will the data in that array still be reliably available and intact? If I put the array into a SAVE statement within the subroutine would that make any difference?

Regards,
Peter
 

0 Kudos
4 Replies
Highlighted
62 Views

See the IVF documentation Index | allocatable arrays | Deallocation of Allocatable Arrays

Jim Dempsey

0 Kudos
Highlighted
Black Belt
62 Views

As of Fortran 95, local allocatable variables without the SAVE attribute are automatically deallocated when a RETURN or END statement terminates execution of a procedure.  The next time the same procedure is called, the allocatable variable will start off deallocated, whatever value it may have had previously is gone.

(If the local variable is also the function result variable, the deallocation is deferred till after execution of the innermost construct that references the function.)

Local allocatable variables with the SAVE attribute are not automatically deallocated.  They retain the allocation and definition status from the termination of a previous instance of the procedure into execution of the next instance of the same procedure.  The next time the same procedure is called, the variable will be just as you left it.

Note the above deals with allocatable variables, not pointer variables.

0 Kudos
Highlighted
Novice
62 Views

Fantastic, thanks.

0 Kudos
Highlighted
62 Views

IanH,

>>(If the local variable is also the function result variable, the deallocation is deferred till after execution of the innermost construct that references the function.)

Is significantly better description than that in the IVF documentation.

Jim Dempsey

0 Kudos