return value as an allocatable array
Tobias Burnus
burnus@net-b.de
Tue Oct 28 17:49:00 GMT 2008
Hi Raju,
Kamaraju S Kusumanchi wrote:
> Let's say I have a function where the return value is an allocatable
> array.
>
[...]
> It creates an array (for the return value) but never deallocates it.
> Will this create a memory leak if I keep repeatedly calling the
> function (say in a do loop)?
>
In principle not. Fortran is designed such that ALLOCATABLE variables
can never leak memory. For
variable = function()
it depends a bit how it is internally handled, but one option would be
to deallocate "variable", allocate it again to the right size and copy
over the values from the function result before the function result
variable is deallocated. Of cause, there are optimizations possible if
the storage size of "variable" is the same as the returned array. Or one
simply deallocates the variable and assigns the function result as
pointer (in the C sense not in the Fortran sense).
In any case, the idea is that it magically works and no memory can leak.
A quite well working technique to test it is to run your program with
"valgrind". Valgrind should report how much memory was leaked.
Having said that, I know that this does not yet work in gfortran to
100%, see for instance
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=35810. Thus it might not
work for your program - even though it should.
Tobias
More information about the Fortran
mailing list