Since Fortran 2003 is it possible to work with variable length character strings. Instead of working in an archaic way and declaring a constant string length I would like to read the character strings of my namelist dynamically.
Consider the program
program bug
implicit none
character(:), allocatable :: string
integer :: file_unit
namelist / list / string
open(newunit=file_unit,file='namelist.txt')
read(unit=file_unit,nml=list)
write(*,*) string
close(file_unit)
end program bug_namelist
and the small namelist contained in the following namelist.txt file:
&list
string = "abcdefghijkl"
/
If I compile with GCC 8.2.0 with agressive debug flags I get
Warning: ‘.string’ may be used uninitialized in this function [-Wmaybe-uninitialized]
and at runtine, nothing is printed and this arises:
Fortran runtime warning: Namelist object 'string' truncated on read.
and with the Intel compiler 17.0.6 with similar debug flags, no compile-time flags and the following runtime error:
forrtl: severe (408): fort: (7): Attempt to use pointer STRING when it is not associated with a target
which indicates that the namelist feature is unable to allocate a variable-length string "by itself", because if I add the line
allocate(character(len=15) :: string)
the errors disappear. Is this expected behavior? Or is it a defect from the compilers?
It is expected behavior, specified by the Fortran standard. In fact, nowhere in Fortran I/O are deferred-length allocatable strings treated the way they are in intrinsic assignment. There is a proposed work item for the next Fortran standard ("F202X") to allow for this in limited contexts (see https://j3-fortran.org/doc/year/18/18-279r1.txt) If I recall correctly, we discussed adding list-directed and NAMELIST reads to this at an earlier standards meeting, but some issues were raised that I don't recall precisely and we will revisit this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With