spectrum
2017-08-25 20:29:20 UTC
Hello,
If we try to reallocate an already allocated ALLOCATABLE
array with allocate() again, it ends up with an error. For example,
the following code
program main
implicit none
integer, allocatable :: a(:), b(:)
b = [1,2,3]
allocate( a(0) )
allocate( a(3), source=b ) !! (*)
print *, "a = ", a
end
gives the error (with gfortran-7.1):
Fortran runtime error: Attempting to allocate already allocated variable 'a'
If we replace the line (*) by
a = b
then the program runs fine with the result (as expected).
a = 1 2 3
Given that automatic reallocation of an allocatable array in the left-hand side
is now standard, I am wondering why allocate() does not perform
automatic deallocation of the old memory on the heap
(if any). Is there any reason why the user is forced to
call deallocate() explicitly for 'a' before calling allocate() (in current Fortran)?
If we try to reallocate an already allocated ALLOCATABLE
array with allocate() again, it ends up with an error. For example,
the following code
program main
implicit none
integer, allocatable :: a(:), b(:)
b = [1,2,3]
allocate( a(0) )
allocate( a(3), source=b ) !! (*)
print *, "a = ", a
end
gives the error (with gfortran-7.1):
Fortran runtime error: Attempting to allocate already allocated variable 'a'
If we replace the line (*) by
a = b
then the program runs fine with the result (as expected).
a = 1 2 3
Given that automatic reallocation of an allocatable array in the left-hand side
is now standard, I am wondering why allocate() does not perform
automatic deallocation of the old memory on the heap
(if any). Is there any reason why the user is forced to
call deallocate() explicitly for 'a' before calling allocate() (in current Fortran)?