Reputation: 1623
I ran across something in someone else's code that seems like it should be undefined behavior in the fortran spec. There is an array defined with an explicit upper and lower bound
ALLOCATE(arraysmall(10,5:10))
This array is passed into a subroutine with the an assumed size dummy argument an explicit index range to work over.
SUBROUTINE foo(arraylarge, indexmin, indexmax)
INTEGER, DIMENSION(10,1:20) :: arraylarge
INTEGER, INTENT(in) :: indexmin
INTEGER, INTENT(in) :: indexmax
...
! Do work from indexmin to indexmax
arraylarge(:,indexmin:indexmax) = ...
END SUBROUTINE
When this subroutine then gets called.
CALL foo(smallarray, 1, 5)
This seems like multiple things are wrong here that should have undefined behavior.
smallarray
and the size of the arraylarge(:,indexmin:indexmax)
have the same have the same size, SIZE(small array, 2) .eq. SIZE(arraylarge(:,indexmin:indexmax),2)
, I would expect that should be accessing unallocated memory since smallarray
isn't defined from indices 1:4. Unless it's doing something like arraylarge(:,1:5) = smallarray(:,5:10)
in the background. But that would seem to me to be something that would be compiler dependent.What should happen when a smaller array is passed into an larger assumed size array? It seems like this should cause a BAD_ACCESS
condition but it isn't.
Upvotes: 0
Views: 512
Reputation: 60123
"Unless it's doing something like arraylarge(:,1:5) = smallarray(:,5:10)
in the background. But that would seem to me to be something that would be compiler dependent."
Indeed, that is happening and it is not compiler dependent. The array is passed as an array of shape (10,5)
and it has lower bounds 1
and 1
. Lower bounds of Fortran arrays are 1 unless declared otherwise. Only allocatable
and pointer
dummy arguments behave differently. So the array is seen in the subroutine as having shape (1:10,1:5)
.
That is why it is not immediately crashing. Still passing an array of shape (1:10,1:5)
to a dummy argument of shape (1:10,1:20)
is not standard conforming. In C they call it undefined behaviour, but Fortran does not use this term. Even if you don't access the elements after 5
bad things can still happen, if temporary array should be passed or similar.
Upvotes: 1