lfortran / lfortran

Official main repository for LFortran
https://lfortran.org/
Other
938 stars 149 forks source link

proposal: add bound check for array dimension #4127

Open kmr-srbh opened 3 months ago

kmr-srbh commented 3 months ago

Both GFortran and LFortran print random garbage values when the array dimension is larger than the actual stored values in an array.


module test_module_dim
   implicit none
   integer(4), save :: nx = 4

end module test_module_dim

program example
   use test_module_dim, only: nx
   implicit none
   integer(4), dimension(6) :: cs

   cs = [1, 2, 3, 4, 5, 6]
   call f(cs)
   nx = 10
   call f(cs)

contains

   subroutine f(x)
      integer(4), dimension(nx), intent(in) :: x

      print *, x
   end subroutine f

end program example
(base) saurabh-kumar@Awadh:~/Projects/System/lfortran$ gfortran ./examples/example.f90 && ./a.out
           1           2           3           4
           1           2           3           4           5           6 -1570274048   779522478 -1300980400       32765
(base) saurabh-kumar@Awadh:~/Projects/System/lfortran$ lfortran ./examples/example.f90
1 2 3 4 
1 2 3 4 5 6 -186771160 32765 1979875664 29636 

GFortran allows this behavior, but should we also allow it? Can we not restrict the values to those actually present in the array, here, 1 2 3 4 5 6 and avoid these garbage values?

The example above uses an array in a subroutine for the demonstration purpose. Variables other than parameter annotated constants should not be allowed to set the dimension of arrays in a program scope due to #4126.

certik commented 3 months ago

In GFortran you have to use -fcheck=all to enable array bounds checking.

In LFortran we also need to add array bounds checking in Debug mode. We'll do that after beta.

Finally, this use case of declaring array dimension using a global variable is a very corner case that I would not worry about it right now. Eventually in Debug mode all these cases will be checked.