Community
cancel
Showing results for 
Search instead for 
Did you mean: 
Highlighted
New Contributor III
10 Views

array bound checking in parameter list of function call

Dear all,

in some cases I pass slices of allocated arrays to functions (in modules -> explicit interface) - who does not ;-).

I have encountered a nasty bug in my code, where - although array bound checking is activated - no exception is thrown by the compiler in runtime (16.0.3, 17.0, x64). I can reproduce this in the following example:

module mod_foo
  use ISO_FORTRAN_ENV, only : rk => real64
  implicit none
  
  private
  public :: rk
  public :: sub_foo
  
  contains
  
  subroutine sub_foo(bar_1, bar_2, bar_3)
    implicit none
    real(rk), dimension(:), intent(in   ) :: bar_1
    real(rk), dimension(:), intent(in   ) :: bar_2
    real(rk), dimension(:), intent(  out) :: bar_3
  
    bar_3(1:10) = bar_1 + bar_2
    
    return
  end subroutine sub_foo
  
end module mod_foo

program array_bounds
    use mod_foo
    implicit none

    ! Variables
    real(rk), dimension(:), allocatable :: bar_1
    real(rk), dimension(:), allocatable :: bar_2
    real(rk), dimension(:), allocatable :: bar_3

    ! Body of array_bounds_or_shape
    print *, 'Hello World'
    
    
    allocate(bar_1(10))
    allocate(bar_2(10))
    allocate(bar_3(20))
    
    bar_1 = 1.0_rk
    bar_2 = 2.0_rk
    
    call sub_foo(bar_1(1:10),bar_2(1:20),bar_3(1:20)) ! this line contains the error: bar_2 has a upper bound of 10!! not captured, why
    
    write(*,'(*(ES12.4))') bar_3
    
    bar_2(20) = 0.0_rk ! this is captured
    
    continue

end program array_bounds

Compiler settings: /nologo /debug:full /Od /warn:interfaces /Qinit:snan /Qinit:arrays /fp:source /module:"x64\Debug\\" /object:"x64\Debug\\" /Fd"x64\Debug\vc140.pdb" /traceback /check:pointer /check:bounds /check:uninit /check:stack /libs:static /threads /dbglibs /c

As commented the call to the function with the obviously wrong bound of bar_2 is not captured, while the bound check two lines below works.

I run the same code under Linux with PSXE 16.0 and GFortran 4.8.3. The Intel version does not throw an exception in the function call line, while GFortran does for the same line:

Fortran runtime error: Index '20' of dimension 1 of array 'bar_2' outside of expected range

It would be nice, if the Intel compilers will catch errors like this. Or is this non-standard Fortran?

Best regards, Johannes

0 Kudos
2 Replies
Highlighted
10 Views

What happens when you change sub_foo, bar_2 to have intent(inout), then add at line 18, bar_2(15) = 1.0?

IOW actually use a location that is out of bounds.

Jim Dempsey

0 Kudos
Highlighted
10 Views

The compiler is simply not doing bounds checking for array slices as actual arguments. I have submitted a request that it do so - DPD200415122.

0 Kudos