Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak by returning allocated strings

A suggested solution for returning a variable length string in Fortran was from this question:

  function itoa(i) result(res)
    character(:),allocatable :: res
    integer,intent(in) :: i
    character(range(i)+2) :: tmp
    write(tmp,'(i0)') i
    res = trim(tmp)
  end function

Am I right in my understanding, that the result of this function is never deallocated? So for large numbers and a lot of calls you could run into memory leaks.

So what I mean exactly is the case where I don't assign the result of my function, but use it "In place" as in

do i = 1, n
    write(*, *) "tmp_"//itoa(i)
end do

I clearly have no reference to the result on which I could call deallocate and while I am looping it definitely doesn't go out of scope.

If I understand you (@Francescalus) correctly, I can still rely on the fact that it is deallocated.

like image 780
mcocdawc Avatar asked Oct 26 '25 06:10

mcocdawc


1 Answers

This question is a specific case of this other one, but being specific it allows us to be more precise. You should read the answers over there for more general detail.

There is no memory leak expected in a correct implementation. The Fortran standard addresses these results explicitly. In Fortran 2008, for example, Note 12.41 says:

The function result is similar to any other entity (variable or procedure pointer) local to the function subprogram. Its existence begins when execution of the function is initiated and ends when execution of the function is terminated. However, because the final value of this entity is used subsequently in the evaluation of the expression that invoked the function, an implementation may wish to defer releasing the storage occupied by that entity until after its value has been used in expression evaluation.

When an allocatable function result's existence ends it is deallocated. This happens for all allocatable results, not just deferred length strings.

So, the memory may "leak" for a little while, but one should expect reclamation fairly promptly. Many levels of function evaluations may cause problems - but you've probably got nasty code long before then.

like image 76
francescalus Avatar answered Oct 29 '25 01:10

francescalus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!