I am trying to use a variable length string to read some data from NetCDF. In order to use the NetCDF calls I must provide a string large enough to accommodate the data. But I am running into problems.
I stripped down the problem in a weird behavior of the gfortran compiler. At least I think it is so, but maybe it is a Fortran 90 feature.
Here is the sample code:
program test
implicit none
integer clen,slen
character(len=:), allocatable :: string
clen = 10
allocate(character(len=clen) :: string)
slen = len(string)
write(6,*) 'clen,slen,dlen: ',clen,slen,len(string)
string = ' '
write(6,*) 'clen,slen,dlen: ',clen,slen,len(string)
string = 'test'
write(6,*) 'clen,slen,dlen: ',clen,slen,len(string)
end
I would expect to get for all three write statements "10 10 10", since the string I have allocated is of size 10.
However, here is what I get:
clen,slen,dlen: 10 10 10
clen,slen,dlen: 10 10 1
clen,slen,dlen: 10 10 4
It seems as if string gets reallocated every time I assign to it. This is not the behavior I expect.
I probably use an outdated version of gfortran (GNU Fortran (Debian 4.9.2-10) 4.9.2). My question is: will this behavior go away with a newer version of the compiler, or is this a feature of Fortran 90? And if this is a feature, how can I avoid it?