| 本帖最后由 愤怒的三炮 于 2024-5-27 13:21 编辑 
 下面一段测试代码中,Function可能会造成内存泄露。说是“可能造成”,是因为在一台8G内存的机器上使用Visual Studio发生了内存泄露,但另一台40G内存的机器上的VS就没有泄露,不知道具体是什么门道,请前辈给点意见。
 
 
 [Fortran] syntaxhighlighter_viewsource syntaxhighlighter_copycode program main
    integer:: a(1000,1000), b(1000,1000) !没有用allocatable,直接声明,不知道有何影响
  
    a = 1
    do i = 1, 5000
        b = func(a)
    end do
    
    contains
    
         function func(arg) result(output)
        
            integer,intent(in):: arg(:,:)
            integer,allocatable::output(:,:)
       
           allocate(output(SIZE(arg,dim=1),SIZE(arg,dim=2)))!此处内存泄露,output没有自动释放
            output = arg + 1
            
        end function
end program
 如果我把主程序中的 a,b 数组声明为allocatable的,经测试,几台机器上都没有发生内存泄露,即
 
 无泄露机器上的编译器版本 Intel(R) Fortran Compiler for applications running on Intel(R) 64, Version 2024.0.0 Build 20231017[Fortran] syntaxhighlighter_viewsource syntaxhighlighter_copycode program main
    integer,dimension(:,:),allocatable:: a,b
    allocate(a(1000,1000), b(1000,1000))
  
    a = 1
    do i = 1, 5000
        b = func(a)
    end do
    
    contains
    
         function func(arg) result(output)
        
            integer,intent(in):: arg(:,:)
            integer,allocatable::output(:,:)
       
           allocate(output(SIZE(arg,dim=1),SIZE(arg,dim=2)))!此处无内存泄露,每次返回后output自动释放
            output = arg + 1
            
        end function
end program有泄露机器上的编译器版本 Intel(R) Fortran Compiler for applications running on Intel(R) 64, Version 2024.1.0 Build 20240308
 
 
 
 
 |