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.