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,
   Marco

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

contains

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

   allocate(z%x(size(x%x)))
   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

   allocate(y%x(size(x%x)))
   y%x = x%x
 end subroutine tt_def

end module mm

program test

 use mm

 implicit none

 type(tt) :: a,b,c

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

 c = a+b

 deallocate(a%x,b%x,c%x)

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.

See: http://groups.google.com/group/comp.lang.fortran/browse_frm/thread/2cb7401441ee0a2d?hl=nl#

Regards,

Arjen
.



Relevant Pages