An error occurred when `gfortran/flang-old` used `associate` to receive an `allocatable` string

The following code runs normally in ifort/ifx, but reports an error in gfortran/flang-old:

program main
    implicit none

    associate(txt_file => get_strings())
        print *, txt_file
    end associate

contains

    function get_strings()
        character(:), allocatable :: get_strings

        get_strings = 'a.txt'

    end function get_strings
  
end program main

Seems to be a bug in gfortran/flang-old? Using associate(txt_file => (get_strings())) seems to work.

>> ifort main.f90 && ./a.out
 a.txt
>> gfortran main.f90 && ./a.out 
 a.txt
free(): double free detected in tcache 2

Program received signal SIGABRT: Process abort signal.

Backtrace for this error:
#0  0x7f5acff58ad0 in ???
#1  0x7f5acff57c35 in ???
#2  0x7f5acfd4f51f in ???
        at ./signal/../sysdeps/unix/sysv/linux/x86_64/libc_sigaction.c:0
#3  0x7f5acfda3a7c in __pthread_kill_implementation
        at ./nptl/pthread_kill.c:44
#4  0x7f5acfda3a7c in __pthread_kill_internal
        at ./nptl/pthread_kill.c:78
#5  0x7f5acfda3a7c in __GI___pthread_kill
        at ./nptl/pthread_kill.c:89
#6  0x7f5acfd4f475 in __GI_raise
        at ../sysdeps/posix/raise.c:26
#7  0x7f5acfd357f2 in __GI_abort
        at ./stdlib/abort.c:79
#8  0x7f5acfd966f5 in __libc_message
        at ../sysdeps/posix/libc_fatal.c:155
#9  0x7f5acfdadd7b in malloc_printerr
        at ./malloc/malloc.c:5664
#10  0x7f5acfdb012a in _int_free
        at ./malloc/malloc.c:4473
#11  0x7f5acfdb24d2 in __GI___libc_free
        at ./malloc/malloc.c:3391
#12  0x55aa397cb387 in ???
#13  0x55aa397cb3c7 in ???
#14  0x7f5acfd36d8f in __libc_start_call_main
        at ../sysdeps/nptl/libc_start_call_main.h:58
#15  0x7f5acfd36e3f in __libc_start_main_impl
        at ../csu/libc-start.c:392
#16  0x55aa397cb104 in ???
#17  0xffffffffffffffff in ???

I have several bugs open with regards to memory issues related to associate. This one however is very succinct and specific and would be worth reporting (assuming it hasn’t been already).

1 Like

Interestingly, ifort seems to have some bugs as well when I use the other two examples:

character(:), allocatable :: dir

dir = 'a/'
associate (file => (dir//'1.txt'))
    print *, file
end associate

end

Whether file => dir//'1.txt' instead of file => (dir//'1.txt'), the results are consistent.

>> gfortran main.f90 && ./a.out
 a/1.txt
>> ifort main.f90 && ./a.out  # This outputs an empty string?
                              

(See godbolt)
As I understand it, Fortran parenthetical expression associate ( xx => (yy) ) is a deep copy procedure.