Fortran Library Reference

malloc, malloc64: Allocate Memory and Get Address

The malloc() function is called by:

k = malloc( n )

n

INTEGER*4

Input 

Number of bytes of memory  

Return value 

INTEGER*4 or INTEGER*8

Output 

k>0: k=address of the start of the block of memory allocated

k=0: Error

An INTEGER*8 pointer value is returned when compiled for a 64-bit environment with -xarch=v9. See Note below.


Note -

Programs compiled to run on 64-bit environments such as Solaris 7 must declare the malloc() function and the variables receiving its output as INTEGER*8. Portability issues can be solved by using malloc64() instead of malloc() in programs that must run in both 32-bit or 64-bit environments.


The function malloc64() is provided to make programs portable between 32-bit and 64-bit environments:

k = malloc64( n )

n

INTEGER*8

Input 

Number of bytes of memory  

Return value 

INTEGER*8

Output 

k>0: k=address of the start of the block of memory allocated

k=0: Error

These functions allocate an area of memory and return the address of the start of that area. (In a 64-bit environment, this returned byte address may be outside the INTEGER*4 numerical range--the receiving variables must be declared INTEGER*8 to avoid truncation of the memory address.) The region of memory is not initialized in any way, and it should not be assumed to be preset to anything, especially zero!

Example: Code fragment using malloc():


    parameter (NX=1000)
    pointer ( p1, X )
    real*4 X(NX)
    ...
    p1 = malloc( NX*4 )
    if ( p1 .eq. 0 ) stop 'malloc: cannot allocate'
    do 11 i=1,NX
11    X(i) = 0.
    ...
    end

In the above example, we acquire 4,000 bytes of memory, pointed to by p1, and initialize it to zero.

See also "free: Deallocate Memory Allocated by Malloc ".