[Top page] [Rants and Raves] [C.V.] [IBMS computers] [Beowulf Cluster] [Beowulf Cluster Queues] [Home computers] [Gateway computer] [S. America photos] [Dynamic mem in Fortran]

Dynamic memory allocation in Fortran90.


! This is a simple example of dynamic memory allocation
! in Fortran90, 
! 
! J.D. Wright 1998
program mem
      implicit none
      real, pointer, dimension (:) :: w1, w2
      integer :: i, sizemem
!
      write (unit=*, fmt="(a)") "How big?"
      read (unit=*, fmt="(i10)") sizemem
!
      allocate (w1(sizemem), w2(sizemem))
!
      do i = 1, (sizemem)
         w1 (i) = i
         w2 (i) = i
      end do
      print *, w1 (sizemem), w2 (sizemem)
end program mem
!

Dynamic memory allocation in Fortran 77.

This is for comparison with Fortran90, this code is non standard but works on many systems eg SGI, IBM, Cray, however it does not work (yet!!) on g77.
      program mem
      implicit none
      integer malloc,i
      
      pointer (p1, fred)
      pointer (p2, jack)
      integer size
      real fred(*),jack(*)

      print *,'How big?'
      read *,size

      p1 = malloc(4*size)
      p2 = malloc(4*size)

      do i=1,(size)
              fred(i)=i
              jack(i)=i
      end do
      print *,jack(size),fred(size)
      end


One of the problems with these schemes is you have to still know how much to allocate before filling the arrays. One of the ways I get around this is to have allocate a block of 100 fill that, when that is filled I then allocate a second array which is 200, copy the first 100 to the second array then fill the 2nd half of that array. For 300 do the same. Seems pretty inefficent to me however but there we go. Also a problem in that at one point I will need (2xrequired) -100 units of memory allocated. Another way is if I am reading a file that I don't know how long it is I will read it line by line to the end work out how much I need to allocate, allocate it rewind the file and reread, nasty but it works.
Last update: Tue Mar 10 17:06:05 CST 1998 Comments to: jon _at_ sinica.edu.tw
These pages were created using vim -a very much vi-improved.
Opinions on these pages are generally not Academia Sinica's.