[RFC, Fortran, (pr66775)] Allocatable function result

Steve Kargl sgk@troutmask.apl.washington.edu
Thu Jul 9 17:50:00 GMT 2015


On Thu, Jul 09, 2015 at 12:25:18PM +0200, Andre Vehreschild wrote:
> 
> I need your help on how to interpret the standard(s) or how to
> implement handling an allocatable function's result, when that
> result is not allocated by the function.  Imagine the simple
> (albeit artificial) case:
> 
> integer function read_input()
>   read_input = ...
> end function
> 
> integer function getNext()
>   allocatable :: getNext
>   if (more_input_available ()) getNext = read_input()
> end function
> 
> where the function getNext () returns an (automatically)
> allocated result when more_input_available() returns .true..
> Otherwise getNext () returns an unallocated object, i.e.,
> the result's allocation status is .false.. I don't want to
> argue about this design's quality (considering it poor myself). I
> suppose that this code is legal, right?

Code is both valid and invalid.  As you point out, it
depends on the return value of more_input_available().
Also, note, it is always invalid under -std=f95 as it
is using automatic (re-)allocation of the LHS.

> Unfortunately gfortran can not handle it currently.

Whatever gfortran does is "correct", because the code is
invalid in the more_input_available() = .false. case.  It is
the responsible of the programmer to ensure that getNext() has
an allocated and assigned value before it returns.  IHMO,
I think that gfortran should not try to guess what the
programmer might have intended.

Yes, the compiled code may dereference a possibly invalid pointer.
The compiled program should segfault, and the programmer should
fix the Fortran code.

function getNext()
   allocatable :: getNext
   if (more_input_available ())
      getNext = read_input()
   else
      allocate(getNext, source=some_error_code?)
   end if
end function

or

function getNext()
   allocatable :: getNext
   allocate(getNext, source=some_error_code?)
   if (more_input_available ()) getNext = read_input()
end function

-- 
Steve



More information about the Gcc-patches mailing list