我使用指针将一些数组传递给子例程,然后在该子例程内分配该数组并将其发送回第一个子例程。在一个模块中我有这样的东西:
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
。这样你就永远不会出现内存泄漏。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)