Re: pointer components and memory leaks

On 16 sep, 19:06, "mreste...@xxxxxxxxx" <mreste...@xxxxxxxxx> wrote:
Dear all,
   is there a way to overload the operators +, =, ... for a derived
type with pointer components which does not leak memory?

To be more precise, the attached code, according to valgrind, leaks
the memory allocated in tt_sum (which indeed seems reasonable to me).
Is there a way to rearrange this code to avoid memory leaks?

I have to add that 1) in general I can not switch to allocatable
components 2) I think a FINAL procedure might solve the problem, but I
wonder how many compilers support it.

Thank you for any advice,

module mm

 implicit none

 type tt
   real, pointer :: x(:)
   !real, allocatable :: x(:)
 end type tt

 interface operator(+)
   module procedure tt_sum
 end interface

 interface assignment(=)
   module procedure tt_def
 end interface


 function tt_sum(x,y) result(z)
  type(tt), intent(in) :: x,y
  type(tt) z

   z%x = x%x + y%x

 end function tt_sum

 subroutine tt_def(y,x)
  type(tt), intent(out) :: y
  type(tt), intent(in) :: x

   y%x = x%x
 end subroutine tt_def

end module mm

program test

 use mm

 implicit none

 type(tt) :: a,b,c

 a%x = (/ 1.0 , 2.0 , 3.0 , 4.0 , 5.0 /)
 b%x = -2.0

 c = a+b


end program test

In addition to the other responses, you might try to use
a memory pool - I posted a program several weeks ago to demonstrate
that in a similar thread.