Vahid
Vahid

Reputation: 125

Memory leakage issue in FORTRAN when allocating an array inside a subroutine and passing it back

I am using pointers to pass some arrays to a subroutine and then allocate that array inside that subroutine and send it back to the first subroutine. In one module I have something like this:

module call_test
   subroutine bla
      use test
      double precision, dimension(:), pointer :: xyz
   !
      interface boink
        subroutine boink(a) 
        implicit none 
        double precision, dimension(:), pointer :: a 
        end subroutine boink
      end interface boink
   !
      call boink(xyz)
      deallocate(xyz)
   end subroutine bla
end module call_test

and in another module I have:

module test
   contains
   subroutine boink(a) 
      implicit none 
      double precision, dimension(:), pointer:: a 
      allocate(a(10))
   end subroutine boink
end module test

It works fine, but the problem is by doing this process each time, i.e. calling the subroutine bla many times, I am allocating some memory that won't be deallocated which causes me memory issues. Is there any way to deallocate the array "a" in the second module after using it in the first module?

Upvotes: 2

Views: 1536

Answers (2)

Xiaolei Zhu
Xiaolei Zhu

Reputation: 527

It will only be a problem if you allocate the same pointer multiple times without deallocation. You can change the allocation part to first detect if the pointer has already been allocated:

if(associated(a))deallocate(a)
allocate(a(10))

Of course, if you point a to some other variable b that cannot be deallocated, this would cause some serious problems.

If all you need a for is a resizable array, it will probably better to make it allocatable instead of pointer. That way you will never have memory leaks.

Upvotes: 2

M. S. B.
M. S. B.

Reputation: 29391

"bla" calls "boink"` whichs allocates a pointer array. Then "bla1" deallocates it. There is no memory leak. It doesn't matter that the two procedures use different names for the same pointer array.

Why do you have an interface for "boink" in module "call_test" when that module uses module "test", which contains "boink"? The use will make the interface of "boink" known in module "call_test".

Upvotes: 1

Related Questions