[J3] How to check if a function that returns an allocatable is actually allocated

Malcolm Cohen malcolm at nag-j.co.jp
Thu Feb 6 00:15:14 UTC 2025


Hi Daniel,

 

> Am I missing something here?

 

What you are missing is that if you want to *conceptually* have a function
that returns an allocated result or an unallocated one, there are two valid
ways to do this already:

 

1.	Instead of a bare allocatable result, have the result be a derived
type with an allocatable component.
2.	Instead of a function, use a subroutine with an allocatable dummy
argument to receive the value (or not).
3.	Instead of an allocatable function, use a pointer function with
manual deallocation - this is not a good way as it is too easy to leak
memory, but pointer functions do not have the "must be allocated"
requirement.

 

The idea ("use-case") behind allocatable functions was to handle things like
array results where the size of the array cannot be simply calculated on
entry to the function; perhaps the simplest obvious example would be reading
a sequence of values from a file where the end of the values is signalled by
end-of-file or a special token. Pointer functions don't work so well for
this because that would need the caller do the memory handling to avoid
memory leaks, whereas with allocatable, the compiler does all the
book-keeping for you.

 

Cheers,

-- 

..............Malcolm Cohen, NAG Oxford/Tokyo.

 

From: J3 <j3-bounces at mailman.j3-fortran.org> On Behalf Of Daniel Chen via J3
Sent: Thursday, February 6, 2025 2:39 AM
To: Van Snyder via J3 <j3 at mailman.j3-fortran.org>
Cc: Daniel Chen <cdchen at ca.ibm.com>
Subject: [J3] How to check if a function that returns an allocatable is
actually allocated

 

Hello all,

Consider the following code

```

print*, allocated(foo(.true.))     !! Not legal as intrinsic ALLOCATED
requires the 
                                   !! argument to have the ALLOCATABLE
attribute.

real, allocatable :: res           !! The following 3 lines to workaround
it.

res = foo(.false.)                 !! Could be illegal too as reference to
foo is undefined.

print*, allocated(res)



contains

  function foo(condition)

   real, allocatable :: foo

   logical :: condition

   if (condition) then

     allocate(foo)
     foo = 1.0

   end if

  end

end
```

It seems there is not a "easy" way to check if the result of a function that
returns an allocatable is actually allocated as indicated in the code above.
My workaround seems have its own problem as the RHS of the intrinsic
assignment (reference to foo) is undefined.
Am I missing something here? 

Thanks,
Daniel

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mailman.j3-fortran.org/pipermail/j3/attachments/20250206/87b5c62b/attachment.htm>


More information about the J3 mailing list