Software Archive
Read-only legacy content
17061 Discussions

saved the allocatables!

rahzan
Novice
489 Views
Normally the variables in a subroutine are saved from call to call. However, it seems that allocatables are not (and in fact automatically deallocated) upon exit from the subroutine. Is this true?

Here is the context I found this;

subroutine X_X !this happens to be a COM server method
call Y
...
call Y
....
end sub X_X

subroutine Y
real,allocatable:: A(:)
if(firsttime in Y) allocate(A)
call Z(A,sizeA)
end sub Y

subroutine Z(A,sizeA)
real A(sizeA)
...
end sub Z

On second call to Y and hence into Z, the server crashes as soon as anything in Z (or Y, I presume) refers to A. The problem goes away if I allocate and deallocate A every time Y is called.

Is this the correct behavior?

Tim
0 Kudos
5 Replies
Steven_L_Intel1
Employee
489 Views
Yes, that is the correct behavior according to the standard. Please don't depend on implicit SAVE semantics for local variables - use SAVE if that's what you want. The only case where you can omit SAVE (but it doesn't hurt) is non-derived-type variables given an initial value through DATA or an initialization clause. (Derived type variables whose type specifies default initialization are NOT implicitly SAVEd, per the standard.)

Steve
0 Kudos
rahzan
Novice
489 Views
Hot diggity!
Took me 3 hours of fooling w/ it through access/vba tofind this out.

Thanks, Tim
0 Kudos
Intel_C_Intel
Employee
489 Views
I have a reverse problem. In most of my subroutines, the values are preserved between calls, although I don't bank on it. For one application however, I would like to start from scratch each time a subroutine is called. Is there any way of doing this other than resetting all the variables on input? I haven't yet found anything in the textbooks or help - I want a re-initialisation facility.

Bear of little brain
0 Kudos
Steven_L_Intel1
Employee
489 Views
The only way to do this automatically is to make the variable be of derived type, where the type specifies default initialization. For example:


subroutine sub
type mytype
  integer :: i = 0
  end type mytype
type(mytype) localvar
...


Now each time the subroutine is entered, localvar%i will be reset to zero. Of course, it would be simpler to just add the initialization yourself!

Steve
0 Kudos
rahzan
Novice
489 Views
Bear,
Could it be that a PURE declaration do what you want?
0 Kudos
Reply