string - 通过返回分配的字符串导致内存泄漏

标签 string function memory-leaks fortran

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

  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

我的理解是否正确,这个函数的结果永远不会被释放?因此,对于大量和大量调用,您可能会遇到内存泄漏。

所以我的意思是我没有分配我的函数的结果,而是在“就地”使用它的情况
do i = 1, n
    write(*, *) "tmp_"//itoa(i)
end do

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

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

最佳答案

这个问题是this other one的具体案例,但具体化它可以让我们更精确。您应该阅读那里的答案以获取更多一般细节。

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

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.



当可分配函数结果的存在结束时,它会被释放。这发生在所有可分配的结果上,而不仅仅是延迟长度的字符串。

因此,内存可能会“泄漏”一段时间,但人们应该会很快地进行回收。许多级别的函数评估可能会导致问题——但在那之前你可能已经得到了令人讨厌的代码。

关于string - 通过返回分配的字符串导致内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55067420/

相关文章:

java - 我正在尝试从字符串中随机抽取一个单词。 java

javascript - 如果多个动画完成,如何从函数返回

JavaScript 在不同时间执行相同的函数

java - Java 中的弱引用和垃圾收集

ios - 如何阅读仪器泄漏图?

java - 如何合并两个不同的字符串

java - 将字符串拆分为单个单词并忽略其他所有内容

c++ - 函数从字符串转换为 int 时出现运行时错误

c - 我正在学习 "Function callback"并且我的代码中出现了段错误?

java - 是否可以将 'see' 对象图用于垃圾收集?