Community
cancel
Showing results for 
Search instead for 
Did you mean: 
Highlighted
Beginner
16 Views

allocate and deallocate versus call subroutine

Dear all,

I have a question about subroutine arguments:

If I have a subroutine like this one

CALL SUBROUTINE(nElem)

SUBROUTINE(nElem)
REAL, DIMENSION(nElem) :: VECT1
REAL, DIMENSION(nElem) :: VECT2

....

and another one:

SUBROUTINE(nElem)

REAL,ALLOCATABLE,DIMENSION(:) :: VECT1,VECT2


ALLOCATE(VECT1(nElem))
ALLOCATE(VECT2(nElem))

...
...
....

DEALLOCATE(VECT1,VECT2)

 

Are these two procedures equivalent, also from computational time?

I ask this question because I have a program where I call several time a subroutine. I stategy could be allocate VECT1 and VECT2 outside in a specific module, but this does not seems very elegant and could create confusion in future.

Thanks to everyone

 

0 Kudos
1 Reply
Highlighted
Black Belt
16 Views

The answer is "It depends".

Allocating on the stack is convenient, but if nElem is large, you make run into stack problems, or you may have to raise the stack limit.

Allocating on the heap is probably better unless you are using an old compiler. With current compilers, locally allocated variables and arrays are automatically deallocated when you exit the subroutine.

With older compilers, locally allocated variables and arrays may remain allocated after subroutine exit, so you have make sure to deallocate before exiting the subroutine. If your subroutine has lots of error tests and short returns, you have make sure that the deallocation is done in each case before exiting the subroutine.

I suggest a suitable combination: allocation on the stack for small arrays and structures, and allocation on the heap for larger arrays. Furthermore, for large arrays that are used in several modules and subroutines, allocate at the beginning of the program and make them module variables.

0 Kudos