Why you don’t need dynamic arrays in Fortran

In languages such as C, creating large arrays (e.g. 1000×1000) requires the use of the heap, and obviously pointers. If you don’t then you get a wonderful segmentation fault. This is largely because C stores “regular” arrays on the stack, and of course there is limited memory on the stack. Fortran, unlike C, provides work-arounds to avoid the use of dynamic memory. Normal automatic arrays in Fortran are stored on the stack or on the heap, depending on the compiler. GNU Fortran  stores them on the heap, which means size of array is much less of an issue. Below is an example of a Fortran program to create a 2D automatic array with 25,000,000 elements. The array is passed to the subroutine MakeArray() which initializes all the elements to 1, and then to the function SumArray() which sums all the values in the array.

program largeArray
 implicit none
 integer :: n=5000,sum
 integer, dimension(5000,5000) :: theArray

 call MakeArray(n,theArray)
 sum = SumArray(n,theArray)
 write(*,*) 'The array sum = ', sum

contains

subroutine MakeArray(n,A)
  integer, intent(in) :: n
  integer, dimension(n), intent(inout) :: A
  A = 1
end subroutine MakeArray

integer function SumArray(n,A)
  integer, intent(in) :: n
  integer, dimension(n), intent(in) :: A
  integer :: i,j,sum=0
  do i = 1,n
    do j = 1,n
      sum = sum + A(i)
    end do
  end do
  SumArray = sum
end function SumArray
end program largeArray

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s