我正在使用指针将一些数组传递给子例程,然后在该子例程中分配该数组并将其发送回第一个子例程。在一个模块中,我有这样的东西:
module call_test
subroutine bla
use test
double precision, dimension(:), pointer :: xyz
!
interface boink
subroutine boink(a)
implicit none
double precision, dimension(:), pointer :: a
end subroutine boink
end interface boink
!
call boink(xyz)
deallocate(xyz)
end subroutine bla
end module call_test
在另一个模块中,我有:
module test
contains
subroutine boink(a)
implicit none
double precision, dimension(:), pointer:: a
allocate(a(10))
end subroutine boink
end module test
它工作正常,但问题是每次都执行此过程,即多次调用子例程 bla,我正在分配一些不会被释放的内存,这会导致我出现内存问题。在第一个模块中使用后,有什么方法可以在第二个模块中释放数组“a”?
最佳答案
只有在没有解除分配的情况下多次分配同一个指针时才会出现问题。您可以更改分配部分以首先检测指针是否已分配:
if(associated(a))deallocate(a)
allocate(a(10))
当然,如果你指向
a
到其他变量b
不能解除分配,这会导致一些严重的问题。如果您需要
a
for 是一个可调整大小的数组,将其设为 allocatable
可能会更好而不是 pointer
.这样你就永远不会有内存泄漏。
关于pointers - 在子例程中分配数组并将其传回时,FORTRAN 中的内存泄漏问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20291814/