我在本教程中读到,可分配变量在超出范围时会自动释放。我写了一个试用程序来测试这个,我发现 valgrind 说有内存泄漏。我的试用计划是:
program arrays
use, intrinsic :: iso_fortran_env, only: prec=>real64
implicit none
integer, allocatable :: array_1(:)
integer, allocatable :: array_2(:,:)
allocate(array_1(10))
allocate(array_2(10,10))
end program arrays
我编译这个程序(arrays.f90)如下(gfortran版本“GNU Fortran(Ubuntu 5.5.0-12ubuntu1~16.04)5.5.0 20171010”)
gfortran -g -std=f2008 arrays.f90 -o arr
然后运行 valgrind (valgrind ./arr) 我发现
==13293== HEAP SUMMARY:
==13293== in use at exit: 440 bytes in 2 blocks
==13293== total heap usage: 21 allocs, 19 frees, 12,280 bytes allocated
==13293==
==13293== LEAK SUMMARY:
==13293== definitely lost: 440 bytes in 2 blocks
==13293== indirectly lost: 0 bytes in 0 blocks
==13293== possibly lost: 0 bytes in 0 blocks
==13293== still reachable: 0 bytes in 0 blocks
==13293== suppressed: 0 bytes in 0 blocks
==13293== Rerun with --leak-check=full to see details of leaked memory
我对为什么 valgrind 说程序结束后两个数组没有被释放感到困惑。
valgrid 的输出不依赖于我正在使用的编译器的优化级别,这与这个关于 fortran 内存泄漏的问题不同。