Fortran 2003 中的内存泄漏



使用"构造函数"(只是一个静态函数(创建初始化派生类型对象时,我遇到了内存泄漏。

我有两个子例程似乎是等效的,但其中一个有内存泄漏(mult_leak(,而另一个没有(mult_noleak(。

我不明白哪个是区别。

program main
    use lala
    type(mytype) :: mt1, mt2, mt3
    integer :: i
    real, allocatable, dimension(:,:) :: dat
    allocate(dat(1000, 1000))
    dat = 1.5
    do i=1,10000000
        mt1 = creador(dat)
        mt2 = creador(dat)
        mt3 = mult_leak(mt1, mt2)
        if(modulo(i,1000)==0) then
            print*, i, mt3%dat(1,1)
        endif       
    end do
end program
module lala
    type mytype
        integer :: nx, ny
        real, allocatable, dimension(:,:) :: dat
        contains
            private
            procedure :: init
    end type
interface creador
    procedure p_creador
end interface
contains
    subroutine init(this, dat)
        class(mytype) :: this
        real, allocatable, dimension(:,:) :: dat
        integer, dimension(2) :: s
        s = shape(dat)
        this%nx = s(1)
        this%ny = s(2)
        allocate(this%dat, source=dat)
    end subroutine
    function p_creador(dat) result(res)
        type(mytype), allocatable :: res
        real, allocatable, dimension(:,:) :: dat
        allocate(res)
        call res%init(dat)
    end function
    function mult_noleak(cf1, cf2) result(cfres)
        class(mytype), intent(in) :: cf1, cf2
        class(mytype), allocatable :: cfres
        real, dimension(:,:), allocatable :: aux
        allocate(cfres)
        aux=cf1%dat * cf2%dat
        call cfres%init(aux)
    end function
    function mult_leak(cf1, cf2) result(cfres)
        class(mytype), intent(in) :: cf1, cf2
        class(mytype), allocatable :: cfres
        real, dimension(:,:), allocatable :: aux
        aux=cf1%dat * cf2%dat
        cfres = creador(aux)
    end function
end module

我发现当我更改"mult_leak"子例程中的"cfres"定义时,泄漏消失了。

function mult_leak(cf1, cf2) result(cfres)
        class(mytype), intent(in) :: cf1, cf2
        !class(mytype), allocatable :: cfres
        type(mytype), allocatable :: cfres
        real, dimension(:,:), allocatable :: aux
        aux=cf1%dat * cf2%dat
        cfres = creador(aux)
end function

似乎问题在于将构造函数分配给多态实体。

最新更新