我已经实现了一个用Fortran编写的通用链表(genII.f90) http://fortranwiki.org/fortran/show/Linked+list。
我测试它并且一切正常,除了LI_Remove_Head函数似乎没有释放内存的事实。
我在原始模块中添加了函数LI_Destruct(见下文),同样的结果是它没有释放内存。
SUBROUTINE LI_Destruct(List)
implicit none
TYPE(List_Type),INTENT(INOUT),TARGET :: List
TYPE(Link_Ptr_Type) :: Link_current, Link_next
Link_next%P =>List%Head%next
do while (associated(Link_next%P))
Link_current%P => Link_next%P
Link_next%P => Link_next%P%next
deallocate(Link_current%P)
end do
end subroutine LI_destruct
我当然想念一些,所以我的问题是两个: 1-代码中是否有错误?出于什么原因,“deallocate”没有清空记忆?
2-它是否更好,几乎是标准的fortran通用链表?
我添加了下面用于进行测试的简单代码:
PROGRAM test_list
! Defines data and other list(s) and arrays for particles.
USE Generic_List, ONLY : Link_Ptr_Type,Link_Type,List_Type
USE Generic_List, ONLY : LI_Init_List,LI_Add_To_Head,LI_Add_To_Tail,LI_Get_Head,&
LI_Remove_Head,LI_Get_Next,LI_Associated,LI_Get_Len, LI_destruct
IMPLICIT NONE
TYPE:: Particle_data
REAL, dimension(2) :: pos !! Coordinate dimensionali
END TYPE Particle_data
! Definition of the types necessary for the list
TYPE Particle_Node
TYPE(Link_Type) :: Link
TYPE(Particle_data), pointer :: Data
END TYPE Particle_Node
TYPE Particle_Node_ptr
TYPE(Particle_Node), pointer :: P
END TYPE Particle_Node_ptr
! Create array of lists in order to allow classify the particles
TYPE(List_Type), allocatable :: ao_Particle_List(:)
TYPE(Link_Ptr_Type) :: Link
TYPE(Particle_Node_ptr) :: Particle_elem
!-------------------------------------------------------------!
!-------------------------------------------------------------!
INTEGER, parameter :: Npart_test = 1000000 ! , nPart
INTEGER :: i,iter,j,item,nBuffer
REAL :: pos(2)
nBuffer = 5
IF (ALLOCATED(ao_Particle_List)) DEALLOCATE(ao_Particle_List)
ALLOCATE(ao_Particle_List(0:nBuffer))
! Init list used for temporary construction
DO iter=0,nBuffer
CALL LI_Init_List(ao_Particle_List(iter))
ENDDO
DO j=1,NBuffer
DO i=1,Npart_test
pos(1)=i*1.0; pos(2)=j*i
ALLOCATE(Particle_elem%P); ALLOCATE(Particle_elem%P%Data) ! Allocate data before store
Particle_elem%P%Data%pos = pos
! Elem is treated and should be put at head of the list ao_Particle_List(item)
item=j
Link = TRANSFER(Particle_elem,Link); CALL LI_Add_To_Head(Link,ao_Particle_List(item)) ! STORAGE
END DO
END DO
WRITE(*,*) "List is full, see RAM"; READ(*,*)
! Write(*,*) "Destruct list"
DO iter=0,nBuffer
CALL LI_Destruct(ao_Particle_List(iter))
ENDDO
IF (ALLOCATED(ao_Particle_List)) DEALLOCATE(ao_Particle_List)
WRITE(*,*) "List is empty, see RAM"; READ(*,*)
END PROGRAM
感谢所有人, 约翰
答案 0 :(得分:0)
好的问题解决了。由于存在传输操作,似乎无法在LI_DESTRUCT
函数中完成数据。
解除分配链表的正确方法是(与fortran wiki中的示例略有不同):
DO
Link = LI_Remove_Head(ao_Particle_List)
IF(.NOT.LI_Associated(Link))EXIT
User = TRANSFER(Link,User)
!~ WRITE(6,*)User%P%Data%Index,User%P%Data%User_Stuff
DEALLOCATE(User%P%Data)
DEALLOCATE(User%P)
ENDDO