FORTRAN: out of bounds check fails in subroutines? - arrays

I have a rather simple piece of code (reduced to the essentials from bigger program).
I pass an array and the size of the array to a subroutine. I get no error if the passed size does not match the actual size of the array. And I can even manipulate the parts of the array that don't "exist" !!! (I overwrite memory that I shouldn't overwrite).
Here is the subroutine:
subroutine sub(arr, narr)
implicit none
integer, intent(in) :: narr
double precision, dimension(narr) :: arr
integer :: j
do j = 1, narr
! print all the values
write(*, '("Arr[",I0,"] = ",f0.10)') j, arr(j)
! change the values
arr(j) = -10d0
enddo
end subroutine
and here the main program
program main
implicit none
integer, parameter :: narr = 5
! the array is made smaller
double precision, dimension(narr - 2) :: array
integer :: j
! assign values to array
array = (/ (1d0*j, j = 1,narr - 2) /)
! print using the subroutine
print*, "inside subroutine"
call sub(array, narr)
! print outside the subroutine
print *, " "
print *, "outside subroutine"
do j = 1, narr
write(*, '("Arr[",I0,"] = ",f0.10)') j, array(j)
enddo
end program
If I compile with ifort and "-check all" it only catches the error in the main program, but not in the subroutine.
Is there a way to catch also the error in the subroutine ?

Yes. Declare array as dimension(:) in the subroutine -- assumed-shape array. Using this Fortran >90 declaration requires that the procedure interface be known to the caller -- the easiest way is to have the procedure in a module and use that module in the caller. You don't actually need to pass the size of the array to the subroutine -- you can determine it as size(arr). I have left the argument narr to retain the bug.
module MySub
contains
subroutine sub(arr, narr)
implicit none
integer, intent(in) :: narr
double precision, dimension(:) :: arr
integer :: j
do j = 1, narr
! print all the values
write(*, '("Arr[",I0,"] = ",f0.10)') j, arr(j)
! change the values
arr(j) = -10d0
enddo
end subroutine
end module MySub
program main
use MySub
implicit none
integer, parameter :: narr = 5
! the array is made smaller
double precision, dimension(narr - 2) :: array
integer :: j
! assign values to array
array = (/ (1d0*j, j = 1,narr - 2) /)
! print using the subroutine
print*, "inside subroutine"
call sub(array,narr)
! print outside the subroutine
print *, " "
print *, "outside subroutine"
do j = 1, narr
write(*, '("Arr[",I0,"] = ",f0.10)') j, array(j)
enddo
end program

Related

Fortran shape matching rules violated

What am I trying to achieve
Im trying to write a subroutine that takes an Matrix (2D array) as input and prints it nicely to the standard console output.
Problem
error #6634: The shape matching rules of actual arguments and dummy arguments have been violated. ['U']
Code
The subroutine printing the matrix is in this module
Module
MODULE LinearSystems
IMPLICIT NONE
private
...
public showMatrix
...
contains
subroutine showMatrix(a, n, m, name)
implicit none
double precision, dimension(:,:), intent(in) :: a
character, dimension(:), intent(in), optional :: name
integer, intent(in) :: n,m
integer :: i, j
write(*,*) "*** Show Matrix ", name, " ***"
do i = 1, n
do j = 1, m
write(*,'(F8.4)',advance="no") a(i,j)
end do
write(*,*)
end do
end subroutine showMatrix
and the main program calls it
Main Program
program PoisonEquation
...
use LinearSystems
implicit none
double precision, dimension(:,:), allocatable :: u,...
integer :: n = 700
allocate(u(n-1,n-1))
...
call showMatrix(u, n-1,n-1, "U")
I'm looking forward to receive tipps on how to improve this code snipped and get it bug free.
The name dummy argument is an assumed shape array (see the dimension(:) declaration). The "U" literal used for the actual argument is scalar (the error message refers to this literal).
If a dummy argument is an assumed shape array, the rank of the actual argument shall be the same as the rank of the dummy argument (F2018 15.5.2.4p16).
Figure out whether you want to pass/receive an array or a scalar, and fix the code.
Problem solved
The problem was in the character initialisation and after fixing this issue as well as fixing a issue in the main program, which lead to u being deallocated before it was passed to the subroutine the code now works and the subroutine for printing looks like this:
subroutine showMatrix(a, name)
implicit none
double precision, dimension(:,:), intent(in) :: a
character(*), intent(in), optional :: name
integer :: i, j
write(*,*) "*** Show Matrix ", name, " ***"
do i = 1, size(a,1)
do j = 1, size(a,2)
write(*,'(F8.4)',advance="no") a(i,j)
end do
write(*,*)
end do
end subroutine showMatrix

Passing the allocatable array to subroutine in Fortran with MPI [duplicate]

This question already has answers here:
keeping array limits in fortran during subroutine call
(3 answers)
Closed 5 years ago.
I am trying to pass the allocatable array to the subroutine. When I am using the serial version as mentioned in How to pass allocatable arrays to subroutines in Fortran it is working fine. Below is my serial version of code.
module test
contains
subroutine func(a,sqa,n)
implicit none
integer, intent(in) :: n
integer, intent(in), dimension(:,:) :: a
integer, intent(out), dimension(:,:):: sqa
!local variables
integer :: i,j
do i= 1,n
do j = 1,2
sqa(i,j) = a(i,j)*a(i,j)
print *, 'i',i, 'j', j,'sqa(i,j)',sqa(i,j)
end do
end do
end subroutine func
end module test
program main
use test
implicit none
integer :: n,i,j
integer, dimension(:,:), allocatable :: a, sqa
print *, 'enter no of rows'
read *, n
allocate(a(1:n,2))
allocate(sqa(1:n,2))
do i = 1,n
do j = 1, 2
a(i,j) = i +j
print *, 'i =',i,'j =',j, a(i,j)
end do
end do
call func(a, sqa,n)
deallocate(a,sqa)
end program main
When I start to implement using MPI, my parallel version of code is
module test
contains
subroutine func(a,sqa,istart,iend)
implicit none
integer, intent(in) :: istart, iend
integer, intent(in), dimension(:,:) :: a
integer, intent(out),dimension(:,:) :: sqa
!local variables
integer :: i,j
do i= istart, iend
do j = 1,2
sqa(i,j) = a(i,j)*a(i,j)
print *, 'i',i, 'j', j,'sqa(i,j)',sqa(i,j)
end do
end do
end subroutine func
end module test
program main
use test
use mpi
implicit none
integer :: istart, iend, ierr,nproc, procnum, n,&
points_per_thread, i,j
integer, dimension(:,:), allocatable :: a, sqa
integer,dimension(mpi_status_size) :: status
call mpi_init(ierr)
call mpi_comm_size(mpi_comm_world, nproc, ierr)
call mpi_comm_rank(mpi_comm_world,procnum, ierr)
if(procnum == 0)then
print *, 'enter no of rows'
read *, n
end if
call mpi_bcast(n,1,mpi_integer,0,mpi_comm_world, ierr)
points_per_thread = (n + nproc - 1)/nproc
istart = procnum*points_per_thread + 1
iend = min((procnum + 1)*points_per_thread,n)
print *, 'istart ', istart, 'iend', iend, 'procnum', procnum
call mpi_barrier(mpi_comm_world, ierr)
allocate(a(istart:iend,2))
allocate(sqa(istart:iend,2))
do i = istart,iend
do j = 1, 2
a(i,j) = i +j
print *, 'i =',i,'j =',j, a(i,j)
end do
end do
call mpi_barrier(mpi_comm_world, ierr)
call func(a(istart:iend,:), sqa(istart:iend,:),istart,iend)
deallocate(a,sqa)
call mpi_finalize(ierr)
end program main
The above code gives the segmentation fault error. I don't understand the reason for this.
Next, when in my subroutine func I change the declaration of arrays a and sqa to
integer,intent(in):: a(istart:iend,2)
integer, intent(out)::sqa(istart:iend,2)
Now it works fine. I request to kindly help me understand the reason for the error.
Assumed shape dummy arrays make available the extension of the actual arguments inside the function but not their bounds. If the actual bounds are needed inside the function, explicit-shape dummy arrays must be used.

3d array assignment error in fortran segfault

My code is currently breaking when I try to pass an array to another array. I'm using gfortran as the compiler with no special flags. I'm also writing the file as a ".f95". Here's the backbone of the code that's causing the problem:
program foo
integer, parameter :: pp = 16
call fooyoo
contains
subroutine fooyoo
real(kind=pp), allocatable :: f(:,:,:), y_ix(:), r(:)
integer :: ii, jj, nn
nn = 32
r = zoo(nn)
y_ix = r ! this is done because I'm actually allocating two other 1D arrays
do ii = 1, nn
do jj = 1, nn
write(*,*) "crashes here"
f(ii,jj,:) = y_ix
write(*,*) "nothing here"
end do
end do
end subroutine
function zoo(nn) result(r)
integer :: i, nn
real(kind=pp) :: r(nn)
do i = 1, nn
r(i) = i
end do
end function
end program
Probably
do ii = 1, nn
do jj = 1, nn
write(*,*) "crashes on executing the next line because programmer forgot ", &
"to allocate f before trying to set values"
f(ii,jj,:) = y_ix
write(*,*) "nothing here"
end do
end do
In this line
y_ix = r
automatic allocation works because the expression on the lhs is an allocatable array. In
f(ii,jj,:) = y_ix
automatic allocation fails because the expression on the lhs is an array section, not an allocatable array.

finding specific indices with pointer array

I am relatively new to Fortran and break my head about one thing for hours now:
I want to write a subroutine for finding the indexes for specific elements in a real 1D array (given to the routine as input).
I have generated an array with 100 random reals, called arr, and now want to determine the indexes of those elements which are greater than a real value min, which is also passed to subroutine.
Plus, in the end I would like to have a pointer I'd allocate in the end, which I was said would be better than using an array indices containing the indexes once found.
I just didn't find how to solve that, I had following approach:
SUBROUTINE COMP(arr, min)
real, intent(in) :: arr(:)
real, intent(in) :: min
integer, pointer, dimension(:) :: Indices
integer :: i, j
! now here I need a loop which assigns to each element of the pointer
! array the Indices one after another, i don't know how many indices there
! are to be pointed at
! And I dont know how to manage that the Indices are pointed at one after another,
! like Indices(1) => 4
! Indices(2) => 7
! Indices(3) => 32
! Indices(4) => 69
! ...
! instead of
! Indices(4) => 4
! Indices(7) => 7
! Indices(32) => 32
! Indices(69) => 69
! ...
DO i = 1, size(arr)
IF (arr(i) > min) THEN
???
ENDIF
ENDDO
allocate(Indices)
END SUBROUTINE COMP
If succinctness (rather than performance) floats your boat... consider:
FUNCTION find_indexes_for_specific_elements_in_a_real_1D_array(array, min) &
RESULT(indices)
REAL, INTENT(IN) :: array(:)
REAL, INTENT(IN) :: min
INTEGER, ALLOCATABLE :: indices(:)
INTEGER :: i
indices = PACK([(i,i=1,SIZE(array))], array >= min)
END FUNCTION find_indexes_for_specific_elements_in_a_real_1D_array
[Requires F2003. Procedures that have assumed shape arguments and functions with allocatable results need to have an explicit interface accessible where they are referenced, so all well behaved Fortran programmers put them in a module.]
A simple way to get the indices of a rank 1 array arr for elements greater than value min is
indices = PACK([(i, i=LBOUND(arr,1), UBOUND(arr,1))], arr.gt.min)
where indices is allocatable, dimension(:). If your compiler doesn't support automatic (re-)allocation than an ALLOCATE(indices(COUNT(arr.gt.min)) would be needed before that point (with a DEALLOCATE before that if indices is already allocated).
As explanation: the [(i, i=...)] creates an array with the numbers of the indices of the other array, and the PACK intrinsic selects those corresponding to the mask condition.
Note that if you are doing index calculations in a subroutine you have to be careful:
subroutine COMP(arr, min, indices)
real, intent(in) :: arr(:)
real, intent(in) :: min
integer, allocatable, intent(out) :: indices(:)
!...
end subroutine
arr in the subroutine will have lower bound 1 regardless of the bounds of the actual argument (the array passed) (which could be, say VALS(10:109). You will also then want to pass the lower bound to the subroutine, or address that later.
[Automatic allocation is not an F90 feature, but in F90 one also has to think about allocatable subroutine arguments
I think you're on the right track, but you're ignoring some intrinsic Fortran functions, specifically count, and you aren't returning anything!
subroutine comp(arr, min)
real, intent(in) :: arr(:)
real, intent(in) :: min
! local variables
integer, allocatable :: indices(:)
integer :: i,j, indx
! count counts the number of TRUE elements in the array
indx = count(arr > min)
allocate(indices(indx))
! the variable j here is the counter to increment the index of indices
j=1
do i=1,size(arr)
if(arr(i) > min) then
indices(j) = i
j = j+1
endif
enddo
end subroutine comp
Then you can use the array indices as
do i=1,size(indices)
var = arr(indices(i))
enddo
Note that since you are not returning indices, you will lose all the information found once you return--unless you plan on using it in the subroutine, then you're okay. If you're not using it there, you could define it as a global variable in a module and the other subroutines should see it.

Share allocatable Arrays

I have some allocatable arrays which I need to share between some subroutines. I usually would just pass them as arguments or maybe write everything in a Module, but I'm afraid this isn't possible in my situation.
I only write some own subroutines and use subroutines provided and described by an FEM-Solver. So i cannot alter the arguments of this subroutines or wrap them in a Module.
As far as i know it also isn't possible to Build common blocks with array of unknown size at compile time.
Is there something else to pass my arrays?
Update:
At the moment my program environment looks like this:
I have a subroutine, provided by the FEM-program, which is called after each increment, this calls several of my subroutines where I compute some values for each node or for a subset of those.
To display these values in the post-Simulation, i have to pass them to another subroutine. This subroutine is called by the FEM-solver for each node at the end of the increment. So shifting my code to this Subroutine would produce a lot of overhead.
My idea is to compute the values once, store the Values in an array and pass this array to the second subroutine where they will be written to the database of the computation.
Update
Some Pseudo-code:
Assumed from program behaviour:
Program FEM-solver
*magic*
call ENDINC(ar1,ar2)
*something*
do NodeID=1,Sum_Of_Nodes
do valueID=1,Sum_Of_User_Computed_Values !(defined in preprocessing)
call nodeval(NodeID,valueID,Value,ar3,...,arN)
end do
end do
*voodoo*
end program FEM-solver
Written and working:
Subroutine ENDINC(ar1,ar2)
*Computation of some node values*
*Calling of own Subroutines, which compute more values*
*Writing an array with results values for some/each node(s)*
nodersltArr(NodeID,rslt)=*some Value*
end Subroutine ENDINC
Needed, writng the computed Values to the Node solution database:
Subroutine nodeval(NodeID,valueID,Value,ar3,...,arN)
*called for each NodeID and valueID*
value=noderslArr(NodeID,valueID)
end subroutine nodeval
You can pass an allocatable array to procedure that isn't declared to use allocatable arrays, as long as the array is allocated before the call. (Of course, you can't use the array as an allocatable array in the procedure in which it is declared without that property.) Perhaps that will solve your problem. Allocate the array in the code that you write, than pass it as an argument to the FEM solver.
Example code: (I'd normally put the function into a module but you say that you can't do that, so I write an example showing the case of not using a module.)
function MySum ( RegArray )
real :: MySum
real, dimension (:), intent (in) :: RegArray
MySum = sum (RegArray)
end function MySum
program TestArray
implicit none
interface AFunc
function MySum ( SomeArray )
real :: MySum
real, dimension (:), intent (in) :: SomeArray
end function MySum
end interface AFunc
real, dimension (:), allocatable :: AllocArray
integer :: N
real :: answer
write (*, '("Input array size: ")', advance="no")
read (*, *) N
allocate ( AllocArray (1:N) )
AllocArray = 1.0
answer = MySum ( AllocArray )
write (*, *) answer
end program TestArray
---------- EDIT: Second Concept ---------
Sharing an allocatable array between two subroutines, without the calling routine being "aware" of the array.
module MySubs
real, allocatable, dimension (:,:) :: array
contains
subroutine One ( x, y, ... N, M )
integer, intent (in) :: N, M
if ( .NOT. allocated (array) ) allocate ( array (N, M) )
end subroutine One
subroutine Two ( .... )
end subroutine Two
end module MySubs
UPDATE: note: This approach can be used to pass information between the two routines without the main program having access the module ... for the question, without modifying the original main prpgram. Part of the example is how to allocate the arrays: the example does that by having the subroutine that would first use the array test whether the array is allocated -- if not, it allocates the array.
The three examples below all work with gfortran. The second may fail on some compilers as it uses a F2003 feature (allocatable dummy arguments), and not all compilers are 100% F2003 compliant. However, most implement ISO TR 15581 (which includes this feature).
First version, you can use a common pointer to allocatable array.
program hip
implicit none
double precision, dimension(:, :), pointer :: p
common /hiphop/ p
double precision, allocatable, dimension(:, :), target :: a
allocate(a(100, 100))
a(1, 1) = 3.1416d0
p => a
call hop
deallocate(a)
end program
subroutine hop
implicit none
double precision, dimension(:, :), pointer :: p
common /hiphop/ p
print *, size(p, 1), size(p, 2), p(1, 1)
end subroutine
Second version, allocating in a subroutine then calling another. One still needs to declare the array in main program.
program hip
implicit none
interface
subroutine hip_alloc(arr)
double precision, allocatable, dimension(:, :) :: arr
end subroutine
end interface
double precision, dimension(:, :), pointer :: p
common /hiphop/ p
double precision, allocatable, dimension(:, :) :: a
p => null()
print *, "a:", allocated(a)
print *, "p:", associated(p)
call hip_alloc(a)
print *, "a:", allocated(a)
print *, "p:", associated(p)
call hop
deallocate(a)
end program
subroutine hip_alloc(arr)
implicit none
double precision, dimension(:, :), pointer :: p
common /hiphop/ p
double precision, allocatable, dimension(:, :), target :: arr
allocate(arr(100, 100))
arr(1, 1) = 3.1416d0
p => arr
end subroutine
subroutine hop
implicit none
double precision, dimension(:, :), pointer :: p
common /hiphop/ p
print *, size(p, 1), size(p, 2), p(1, 1)
end subroutine
Third version, here we first call a function returning a pointer, then pass this pointer to a subroutine through a common. The function does the allocation, as in second example. The pointer is deallocated in main program, but could be elsewhere.
program hip
implicit none
interface
function hip_alloc(n)
integer :: n
double precision, dimension(:, :), pointer :: hip_alloc
end function
end interface
double precision, dimension(:, :), pointer :: p
common /hiphop/ p
p => null()
print *, "p:", associated(p)
p => hip_alloc(100)
print *, "p:", associated(p)
call hop
deallocate(p)
end program
function hip_alloc(n)
implicit none
integer :: n
double precision, dimension(:, :), pointer :: hip_alloc
allocate(hip_alloc(n, n))
hip_alloc(1, 1) = 3.1416d0
end function
subroutine hop
implicit none
double precision, dimension(:, :), pointer :: p
common /hiphop/ p
print *, size(p, 1), size(p, 2), p(1, 1)
end subroutine
I do not understand why writing a MODULE would not work, but have you considered CONTAINS? Everything above the CONTAINS declaration is visible to the subroutines below the CONTAINS:
PROGRAM call_both
INTEGER,DIMENSION(2) :: a, b
a = 1
b = 2
PRINT *,"main sees", a, b
CALL subA
CALL subB
CONTAINS
SUBROUTINE subA
PRINT *,"subA sees",a,b
END SUBROUTINE subA
SUBROUTINE subB
PRINT *,"subB sees",a,b
END SUBROUTINE subB
END PROGRAM call_both
The output would be
main sees 1 1 2 2
subA sees 1 1 2 2
subB sees 1 1 2 2
This works with ALLOCATABLE arrays as well.

Resources