What is wrong with this code?

Intel Fortran has no problem.
Gfortran has problem.
The cygwin64 gfortran on windows cannot show complete string, it shows things like ''a is bigge".
Gfortran 11.2.0 on ubuntu has the same issue OP mentioned.

I don’t know why, but if you define

character(:), allocatable :: str   

inside a type as below,

  type :: var_char 
    character(:), allocatable :: str   
  end type var_char  

Then the code work with gfortran without problem.
see below code, the !!! are the small modifications.

program main
  use iso_fortran_env, only: dp => real64
  implicit none
  
  type :: var_char !!!!!!!!!!!!!!!
    character(:), allocatable :: str    !!!!!!!!!!!!!!!!!!!1 
  end type var_char   !!!!!!!!!!!!!!!
  
  
  call test_fun1()

contains

  function fun1(a, err) result(b)
    real(dp), intent(in) :: a
    type(var_char) :: err  !!!!!!!!!!!!!!!!!
    real(dp) :: b(2)
    if (a > 2) then
      err%str = 'a is bigger than 2'  !!!!!!!!!!!!!!!!!!!!!
      return
    endif

    b = 1
  end function

  subroutine test_fun1()
    real(dp) :: a, b(2)
    type(var_char) :: err  !!!!!!!!!!!!!!!!!!!!!
    
    a = 3
    b = fun1(a, err)
    if (allocated(err%str)) then  !!!!!!!!!!!!!
      print*,'err is allocated'
      print*,'next line tries to print err'
      write(6,'(a)') err%str !!!!!!!!!!!!!!!!!
    else
      print*,b
    endif
  end subroutine

end program

See a similar topic,

In short, I don’t know why, but if

character(:), allocatable :: str   

needs to be used, it is best to define it inside a type.

2 Likes