Incorrect resizing of Fortran array in loop

Hi,

I found this bug while trying to get our coupled ocean model working with NVHPC. At -O2, when an unallocated allocatable array is sized at the first iteration of a loop, and then resized at a later iteration, the size doesn’t seem to get updated properly - leading to out-of-bounds access and/or wrong answers. See below reproducer:

program repro
  implicit none
  integer, allocatable :: a(:)
  integer :: i, nt, n(2) = [24, 80]
  do i = 1, 2
     nt = n(i)
     if (allocated(a)) then
        if (size(a) /= nt) deallocate(a)
     endif
     if (.not. allocated(a)) allocate(a(nt))
     a(:) = 1
     print *, nt, size(a), sum(a)
  enddo
end program

This program simply allocates a in the first iteration, and then deallocates and reallocates it to a new size in the second iteration. After the loop, a is set to ones and summed.

Compiling and running:

nvfortran -O2 repro.F90 && ./a.out
           24           24           24
           80           80           24
Segmentation fault

The bottom right number should be 80, not 24.

Compiling with -Mbounds:

           24           24           24
0: Subscript out of range for array a (repro.F90: 11)
    subscript=25, lower bound=1, upper bound=24, dimension=1

This is an issue for all the NVHPC versions I tested (24.9 to 26.9 inclusive).

If I switch to use an implied do array assignment (relying on auto reallocation), it seems to run fine

program workaround
  implicit none
  integer, allocatable :: a(:)
  integer :: i, k, nt, n(2) = [24, 80]
  do i = 1, 2
     nt = n(i)
     a = [(1, k = 1, nt)]
     print *, nt, size(a), sum(a)
  enddo
end program
           24           24           24
           80           80           80

Another workaround is to allocate array before the start of the loop.

Thanks for the report Ed!

I was able to reproduce the issue here and filed TPR#39192.

The problem appears to be with an optimization being applied to “size(a)” causing it to return the value “nt”. Which in turn causes the if test to fail and the array not getting deallocated.

Another work around is to replace “size(a)” with “ubound(a,1)”, though I don’t know if that will work in the larger code given it presumes a single dimensional array.

-Mat

FYI, engineering took a first look and suggested another work around could be to use sourced allocation:

program repro
  implicit none
  integer, allocatable :: a(:)
  integer :: i, nt, n(2) = [24, 80]
  do i = 1, 2
     nt = n(i)
     if (allocated(a)) then
        if (size(a) /= nt) deallocate(a)
     endif
     if (.not. allocated(a)) allocate(a(nt),source=1)
     !a(:) = 1
     print *, nt, size(a), sum(a)
  enddo
end program

Thanks mat!

That’s quite useful to know. Upstream has already approved the array assignment form, but I can see adding a source term (like 0) being a good enough workaround in the future.