A bug in the `index` function in gfortran?

When I use the index function in gfortran, when back is true, the index function has an error in solving the position of the first letter of the string. This seems to be a bug. See code:

program main
    character(11) :: str = "fortran.f90"

    print *, index("fortran.f90", ".f90")
    print *, index("fortran.f90", ".f90", back=.true.)
    print *, index("fortran.f90", "fortran")
    print *, index("fortran.f90", "fortran", back=.true.) ! It should get '1'
    print *, index(str, "fortran", back=.true.)

end

Run it:

>> gfortran main.f90 && ./a.exe
8
8
1
0
1
>> ifort main.f90 && ./main.exe
8
8
1
1
1

Unfortunately, I’m not familiar with gcc’s bug submission process, and It seems to I’m not able to register a gcc account using my usual email address. If someone confirms that this is a bug and is familiar with gcc’s bug submission process, and can help, that would be the best!

Rather than a bug in the INDEX function in Gfortran’s RTL being the cause, I think, the error occurs when the expression containing INDEX is being evaluated at compile time (because that is possible) and the resulting value is placed into the a.out/EXE as a constant, to be printed out as requested. Here is a demonstration:

program main
   i = index("fortran.f90", "fortran", back=.true.) ! It should get '1'
   call prnt(i)
contains
   subroutine prnt(i)
   integer i
   print *,'i = ',i
   end subroutine
end program

If you look at the assembly generated by this, you can see that the erroneous value 0 is loaded into the argument ‘i’, which is then passed to subroutine prnt() for printing.

I have made a report to Bugzilla.

The following test program shows that the RTL produces the correct result. Compile and run the program, and enter ‘For’ (without quotes).

program gbug
character(11) :: str = 'Fortran.f90'
character(3) :: s
do
  read(*,'(A)')s
  print *,index(str,s,BACK=.true.)
end do
end program
2 Likes

No argument with the conclusions; but my experience is that it is nice to have a reproducer not
require I/O, so just a tweak to the example:

 program main
implicit none
character(8) :: date
call date_and_time(date=date)
    print *, index("fortran.f90"//'20220522', "fortran", back=.true.)
    print *, index("fortran.f90"//date, "fortran", back=.true.)
end

and at least GNU Fortran (Ubuntu 10.3.0-1ubuntu1~20.04) 10.3.0
gives “0 1”.

EDIT: I see the Bugzilla report does not require I/O anyway.

2 Likes