| pointer components and memory leaks |
|
 |
|
 |
|
 |
|
 |
Group: comp.lang.fortran · Group Profile
Author: mrestellimrestelli Date: Sep 16, 2008 10:06
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
|