通过返回分配的字符串导致内存泄漏 [英] Memory leak by returning allocated strings

查看:89
本文介绍了通过返回分配的字符串导致内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Fortran中返回可变长度字符串的建议解决方案来自这个问题:

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

我显然没有提到可以调用deallocate的结果,并且在循环时绝对不会超出范围.

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.

如果我正确地理解了您(@Francescalus),我仍然可以依靠它已被释放的事实.

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

推荐答案

此问题是另一个人的一个具体案例,但具体而言,它可以使我们更加精确.您应该在那儿阅读答案,以获取更多常规信息.

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.

在正确的实现中不会出现内存泄漏. Fortran标准明确地解决了这些结果.例如,在Fortran 2008中,注释12.41说:

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.

这篇关于通过返回分配的字符串导致内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆