Unfreed allocatable class memory
John McFarland
mcfarljm@gmail.com
Sun Jun 16 14:27:00 GMT 2019
Hi,
I came across the below scenario in which it seems to be possible to
allocate unfreeable memory using a function that returns an
allocatable class instance. I eventually discovered that the memory
leak is eliminated by having the function return a "type" instead of
"class" (presumably the right way to write the code, although I admit
to being a little fuzzy on the best way to create these kind of
constructors). But I figured it might still be worth pointing this
out, as it seems to make it possible to allocate memory that cannot be
freed.
Tested with gfortran 8.3.0. Valgrind indicates that the line
"allocate(childa_new)" causes 4 bytes to be lost (which I believe is
the integer component "x").
John
Code follows:
MODULE mymod
IMPLICIT NONE
TYPE :: ChildAType
INTEGER :: x
END TYPE ChildAType
INTERFACE ChildAType
PROCEDURE :: childa_new
END INTERFACE ChildAType
CONTAINS
FUNCTION childa_new(x)
INTEGER, INTENT(in) :: x
! Eventually discovered that using CLASS here was the culprit. When
! this is changed from CLASS to TYPE, the leak goes away.
CLASS (ChildAType), ALLOCATABLE :: childa_new
ALLOCATE(childa_new)
childa_new%x = x
END FUNCTION childa_new
END MODULE mymod
PROGRAM prog2
USE mymod
CLASS (ChildAType), ALLOCATABLE :: b
! Either of these two produces a memory leak
ALLOCATE( b, source=ChildAType(2) )
!b = childa_new(2)
DEALLOCATE( b )
END PROGRAM prog2
More information about the Fortran
mailing list