Closed d7919 closed 1 year ago
Agreed. Similar failures can happen under other circumstances. Been a long time since I had to look at this layer - really should not have any hardcoded lengths at all. (Early days allocatable strings were sometimes wonky and I had to use workarounds.)
Just back from a long bit of travel, so might be a week or more before I can dive into this. But if you see a fix already, feel free to submit a PR (onto develop
branch please).
It's difficult to work out the required length of the allocatable string to represent the real data in advance. There are two slightly hacky workarounds that I can think of immediately:
len_trim
to determine the actual size required to use to allocate strings. Questionable if there's much advantage to copying out from the excessive size into the allocatable character.eor
option to write
to detect if the string is insufficient in size and reallocate to a larger string.The second would look something like
character(len=:), allocatable :: string
integer :: length
length = 8
10 length = length * 2
if (allocated(string)) deallocate(string)
allocate(character(len=length) :: string)
write(string, '(g0)', eor = 10) e
Edit: My mistake eor
is only applicable to read
, not write
. One can still do something similar, although it's even uglier
use iso_fortran_env, only: iostat_eor
character(len=:), allocatable :: string
integer :: length, iostat
length = 8
iostat = iostat_eor
do while(iostat == iostat_eor)
length = length * 2
if (allocated(string)) deallocate(string)
allocate(character(len=length) :: string)
write(string, '(g0)', iostat = iostat) e
end do
Note this then hides/ignores any other error condition which arises and one may need additional handling of iostat
to check success or otherwise.
Yeah. I've done something similar to this in my logging package where one really has no idea in advance of the size of the strings, as even the format is a run-time entity.
In a test case using
real128
kinds it is possible for the test driver to fail withI believe this is because
expected_str
is declared ascharacter(len=MAX_LEN_REAL_AS_STRING)
whereMAX_LEN_REAL_AS_STRING = 40
is not quite long enough to contain the desired string.As an example
aborts as above. Changing
MAX_LEN_REAL_AS_STRING
to 43 sees the test correctly fail with the desired error message:The maximum value required could of course be larger than 43 if the exponent, were longer say.