Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read an allocatable string with a namelist in Fortran

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?

like image 662
circuitbreaker Avatar asked Mar 06 '23 04:03

circuitbreaker


1 Answers

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.

like image 72
Steve Lionel Avatar answered Mar 27 '23 03:03

Steve Lionel