问题
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.
回答1:
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.
回答2:
You are only right to believe that the result is never deallocated if your code never deallocates it or, perhaps more relevant, if it never goes out of scope. But a memory leak only occurs when you lose the last reference to the allocated memory, and it's actually quite difficult to do that in modern Fortran, especially so for allocatable variables, but slightly easier with pointers.
If the variable is allocated within the scope of another routine it will be reaped by the operating system ('cos that's what the Fortran standard says must happen) when the routine finishes. And if it is in the program scope and is never deallocated, it is not a memory leak.
来源:https://stackoverflow.com/questions/55067420/memory-leak-by-returning-allocated-strings