I have seen several questions about passing unallocated arrays into functions or subroutines that cause runtime faults where the recommended solution was to allocate it in the calling procedure with zero length. I did some experiments:
program test
integer, allocatable :: A(:)
allocate(A(3))
print*, size(A)
deallocate(A)
allocate(A(-5:-3))
print*, size(A)
deallocate(A)
allocate(A(0))
A(0) = 9
print*,A(0),'Size:',size(a)
deallocate(a)
allocate(A(-4))
print*,size(A)
deallocate(A)
allocate(A(-4:-4))
print*,size(A)
end
The first one is obvious. An array of length 3. The second one takes advantage of a cool feature of Fortran, defining your own index limits. It is an array of length 3 with the elements A(-5), A(-4), and A(-3).
Third one gets dicey. I allocate it with a zero. I can assign a value! It prints: 9 Size: 0
The fourth one prints a size of zero too!
Apparently, the correct way to allocate an array of length 1 with an index of -4 is the last one.
Question: On the third and fourth ones, did I just write to memory that likely belongs to some other variable (except of course this example has no other variables)?