[comp.lang.fortran] dynamic memory allocation

keinert@IASTATE.EDU (Keinert Fritz) (05/17/91)

I have found an easy way to create Fortran storage dynamically. This
method depends on some undocumented features of the MIPS f77 version
2.1 compiler that I just stumbled across by accident. In other words:
not for the timid, and not portable. However, with one minor 
modification it also compiled and ran on a Sun 3/60 f77, version 4.1.
It may work on your machine, too.

Specifically, the undocumented features in MIPS Fortran are

- the "pointer" data type, apparently borrowed from Cray Fortran;
(see separate posting about that)

- the fact that f77 can handle the malloc() and free() system calls
directly from Fortran code, instead of through a C interface;

Another possibly nonportable construction is the "%val" syntax for passing
arguments by value, borrowed from VAX Fortran. That one is documented.

Suppose subroutine sub(n,m) needs an array A(n,m) as work storage.
The raw storage is created and later destroyed in sub(), and sub2()
does the actual work:


	subroutine sub(n,m)
	integer  n, m
	real     A
	pointer  (pA,A)
	pA = malloc(%val(4*n*m))
	if (pA .eq. 0) then
	    print*,'storage allocation failed'
	    stop
	endif
	call sub2(n,m,A)
	free(A)
	end

	subroutine sub2(n,m,A)
	integer n, m
	real    A(n,m)
	...

In principle, you don't need sub2, but pointer handling in Fortran is
extremely clumsy.  I would just as soon let the compiler handle the
index arithmetic for A(i,j).

This program will also run on Sun Fortran, except that "malloc" uses a
call by reference there. In other words: take out the "%val" in the
argument to "malloc".
--
Fritz Keinert                             phone:  (515) 294-5128
Department of Mathematics                 fax:    (515) 294-5454
Iowa State University                     e-mail: keinert@iastate.edu
Ames, IA 50011