1

I have a simple example of a code with two matrices, mat and mat2. mat is allocatable, the two matrices are constructed with 2X2 size.

program example
  double precision , dimension(:,:), allocatable :: mat
  double precision mat2(2,2)
  integer nx,ny

  nx=2
  ny=2
  allocate(mat(nx,ny))
  mat(1,1)=1.d0
  mat(1,2)=2.d0
  mat(2,1)=3.d0
  mat(2,2)=4.d0

  mat2(1,1)=1.d0
  mat2(1,2)=2.d0
  mat2(2,1)=3.d0
  mat2(2,2)=4.d0

  write(*,*) mat(4,1)
  write(*,*) mat2(4,1)
end program example

When compiling and executing the code using ifort (ifort version 2021.1), no error or warning is shown. The result is

 4.00000000000000
 4.00000000000000

When compiling and executing the code using gfortran, a warning appears :

main.f90:21.20:

  write(*,*) mat2(4,1)
                1
Warning: Array reference at (1) is out of bounds (4 > 2) in dimension 1

However, the execution gives the same result. I expected a segmentation fault error. This make debugging a complex program very difficult, since no error appear with this kind of error. Is this a normal behavior?

  • 2
    The compiler has been very nice to you, and warned you that your code is invalid. However, as the linked question and its answers say, you can't expect a segmentation fault or anything else. You may, however, be able to turn on runtime diagnostics (bounds checking) which will cause the program to fail. (Also note that in terms of index arithmetic, `mat2(4,1)` is unlikely to fall beyond the memory of `mat2`.) – francescalus Aug 05 '21 at 15:13

0 Answers0