Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
28507 Discussions

determining the largest possible array allocation size in Fortran

Valued Contributor I

Suppose I wanted to measure, at runtime, the size of RAM available for an array allocation. The only Fortran-bound solution that I can think of, involves randomly (binary) searching for the maximum possible allocation and checking for zero status error, like the following code.

program hello
    real, allocatable   :: array(:,:,:)
    integer             :: ierr, i
    i = 1000000
        allocate(array(i,i,i), stat = ierr)
        if (ierr == 0) exit
        if (i < 2) then
            write(*,*) "Nothing could be allocated."
            error stop
        end if
        i = i / 2
    end do
   write(*,"(*(g0,:,' '))") "allocated size = (", i, ",", i, ",", i, ")"
end program Hello


What are the pitfalls of the above approach and what alternatives do exist in Fortran? Could lazy allocation become problematic in the above solution?


0 Kudos
1 Reply
Honored Contributor I

I am quite sure that:

  • this is not a reliable method, for instance because of the lazy allocation you mention, but also because of other processes running at the same time;
  • you get an answer one way or another and that may be useful enough.
  • it all depends on the details of the memory management of the operating system and of your hardware

The point, however, is why do you want to know this at run-time? If your program requires the memory, then a failure to allocate that is the end of the exercise. If your program requires it, but could do the job with an alternative strategy requiiring less memory, then the failure can be used to choose that alternative. I see little point in trying to establish the maximum available memory, but that is merely me ;).