https://gcc.gnu.org/bugzilla/show_bug.cgi?id=98490
Bug ID: 98490 Summary: Unexpected out of bounds in array constructor with implied do loop Product: gcc Version: 9.3.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: fortran Assignee: unassigned at gcc dot gnu.org Reporter: ffadrique at gmail dot com Target Milestone: --- The followinng code, when compiled with -fbounds-check produces a runtime exception program test implicit none call sub( 'Lorem ipsum' ) contains subroutine sub( text ) character(len=*), intent(in) :: text integer :: i write(*,*) [ ( text(i:i), i = 1, len(text) ) ] end subroutine sub end program test Run time error: At line 18 of file test.f90 Fortran runtime error: Substring out of bounds: lower bound (-2147483648) of 'text' is less than one Error termination. Backtrace: #0 0x7f01d0965d3a #1 0x7f01d0966849 #2 0x7f01d0966ec6 #3 0x5567acbd1269 #4 0x5567acbd14e6 #5 0x5567acbd151e #6 0x7f01d077a0b2 #7 0x5567acbd10fd #8 0xffffffffffffffff It is clear to me that the automatic variable i is not initialised before invoking the implied do loop. However, the loop should run between 1 and the length of the input text as given in the loop controls; not evaluate at the uninitialised value. The behaviour is as expected when not compiled with the bound check flag. Also valgrind is not reporting any invalid memory access. The issue may be associated to the compilation with the bound check flag (that I need to have enabled in general). The workaround is straightforward. I have also checked that if there were several statements like the write one in the example, I would have to control the initial value of i before each implied loop to make sure that the initial value is not out of the array in the loop. i = 1 ! Prevents the exception write(*,*) [ ( text1(i:i), i = 1, len(text1) ) ] ! text1 of length 20 ! Next statement triggers the exception unless i is reset again write(*,*) [ ( text2(i:i), i = 1, len(text2) ) ] ! text2 of length 10