I'm trying to solve a memory leak in a Fortran program and I'm seeing some issues with finalization routines. The following example illustrates the issue that I found:
module MemLeaksMod implicit none type :: ComponentType private real :: value contains final :: FinalizeComponent end type ComponentType type :: ContainerType class(ComponentType), allocatable :: component contains final :: FinalizeContainer end type ContainerType contains subroutine FinalizeContainer(this) type(ContainerType), intent(inout) :: this print *, "Finalizing container class" end subroutine FinalizeContainer subroutine FinalizeComponent(this) type(ComponentType), intent(inout) :: this print *, "Finalizing component class" end subroutine FinalizeComponent end module MemLeaksMod program MemLeaksProg use MemLeaksMod implicit none call TestMemLeaks() contains ! Shows that the finalizer of the componentType class isn't called if the containerType class doesn't have a finalizer: subroutine TestMemLeaks type(ContainerType) :: container allocate(container%component) end subroutine TestMemLeaks end program MemLeaksProg
When running the program, I get the following output:
Finalizing container class
Finalizing component class
This is what I expect. Now if I comment out the
final :: FinalizeContainer
statement for the container type, I would expect that the finalizer for ComponentType is still called. However, when running the modified code, it shows now output, so the finalizer for ComponentType wasn't called.
Is this a bug in the intel compiler or is it the expected behaviour? For me it seems that calling the ComponentType finalizer shouldn't depend on the presence of a finalizer on the ContainerType.
Another question related to finalizers. If a type has allocatable components and implements a finalizer, should the finalizer deallocate the allocatable components, or will this be done automatically (as is the case if no finalizer was implemented at all)? I tried to find the answer in "Model Fortran Explained", but it wasn't clear on this subject.