Unfreed allocatable class memory

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Unfreed allocatable class memory

John McFarland-2
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
Reply | Threaded
Open this post in threaded view
|

Re: Unfreed allocatable class memory

Dominique d'Humières-2
AFAICT this fixed in GCC9 and trunk (10.0).

Cheers,

Dominique