[comp.lang.fortran] Dynamic Memory Allocation Solution

glenn@qed.physics.su.OZ.AU (Glenn Geers) (12/22/90)

Hi,
	this is my first posting to this group although I've been reading it for
some time. I'm primarily a C programmer but some of my grad work requires
writing code that heavily uses complex numbers (Solution of 2d vector wave
equation in an anisotropic optical fibre). At present I allocate 2-d arrays
of structs in C (anyone wanting code can drop me a line) and perform the
numerical calcs in FORTRAN routines.

Anyway to cut a long story short I found that on our SUN machines the following
code will work:

		program t

		double precision i

		i=malloc(24000)

 c  24000 bytes .eq. 3000 double precision 
		call p(i,3000)

		call free(i)

		stop
		end

		subroutine p(i, isize)
		double precision i(isize)

		i(10)=5.0
		i(2999)=10.0
		write(*,*) i(10), i(2999)

		return
		end

If the call to malloc is omitted the code will fail (fair enough!).

At home I have a 386 box running Sys V 3.2 and my FORTRAN development system
is f2c which does not support the code above. So I hacked the following trivial
routines and lo and behold it works exactly as on our SUN machines. 


int
malloc_(num)
int *num;
{
	return((int)malloc(*num));
}

void
free_(num)
int *num;
{
	free(num);
}

Note that I should do error checking and return 0 if the amount of memory
requested cannot be obtained. Also note that this is shocking programming
practice - I'm assuming sizeof(int) == sizeof(int *) which holds on 32 bit
machines and small model 8086 code. On other machines I have no idea (it
would probably work on a pdp11 where sizeof(int) == sizeof(int *) 
= 16 bits). If anyone tries this on some OS other than UNIX and on other
than an 80386(486) in 32 bit mode I'd like to know how it goes.

And as for the religious war between FORTRAN and C: both have advantages and
disadvantages. So I use both to get maximum use of the facilities available.

I hope someone finds this useful.
Share and enjoy,
		Glenn

glenn@qed.physics.su.oz.au

--
Glenn Geers                       | "So when it's over, we're back to people.
Department of Theoretical Physics |  Just to prove that human touch can have
The University of Sydney          |  no equal."
Sydney NSW 2006 Australia         |  - Basia Trzetrzelewska, 'Prime Time TV'