Fortran: Memory Allocation


One feature that standard FORTRAN 77 lacked was dynamic memory allocation. As with a number of features, this was added by specific implementations in order to make the language more flexible. In order to allocate memory dynamically using the GFortran compiler, you can use the Cray pointer extension:

      program da
      implicit none
      integer malloc,size,i

      pointer (ptr, arr)
      real arr(*)

      print *,'Array size?'
      read *,size

      ptr = malloc(4*size)

      do i=1,(size)
              arr(i)=i*size
      end do

      do i=1,(size)
              print *,'Element',i,'value',arr(i)
      end do

      end

To compile this FORTRAN 77 style program using GFortran, use the following command:

$ gfortran -ffixed-form -fcray-pointer -o da da.f

The pointer declaration indicates that ptr points to the array arr. Scalar elements may be pointed to as well as arrays. As shown, the declaration of a pointer may occur before the declaration of the element it points to. To allocate memory, the malloc() intrinsic can be used. To assign the address of an element to a pointer, the loc() intrinsic can be used (it provides similar functionality to the & operator in C).