FORTRAN 77 Language Reference

Address and Memory

No storage for the variable is allocated when a pointer-based variable is defined, so you must provide an address of a variable of the appropriate type and size, and assign the address to a pointer, usually with the normal assignment statement or data statement.

The loc(), malloc(), and free() routines associate and deassociate memory addresses with pointers. (These routines are described in Chapter 6.)

When compiled for 64-bit environments, pointers declared by the POINTER statement are INTEGER*8 values.

Address by LOC() Function

You can obtain the address from the intrinsic function LOC().

Example: Use the LOC() function to get an address:

* ptr1.f: Assign an address via LOC() 
	POINTER ( P, V ) 
	CHARACTER A*12, V*12 
	P = LOC( A ) 
	PRINT *, V(5:5) 

In the above example, the CHARACTER statement allocates 12 bytes of storage for A, but no storage for V. It merely specifies the type of V because V is a pointer-based variable, then assign the address of A to P, so now any use of V will refer to A by the pointer P. The program prints an E.

When compiled for 64-bit environments, LOC() returns an INTEGER*8 value. The receiving variable must be either a pointer or an INTEGER*8 variable to avoid possible address truncation.

Memory and Address by MALLOC() Function

The function MALLOC() allocates an area of memory and returns the address of the start of that area. The argument to the function is an integer specifying the amount of memory to be allocated, in bytes. If successful, it returns a pointer to the first item of the region; otherwise, it returns an integer 0. The region of memory is not initialized in any way.

Example: Memory allocation for pointers, by MALLOC

	POINTER ( P1, X ), ( P2, Y ), ( P3, Z ) 
	P1 = MALLOC ( 10000 ) 


In the above example, MALLOC() allocates 10,000 bytes of memory and associates the address of that block of memory with the pointer P1.

Deallocation of Memory by FREE() Subroutine

The subroutine FREE() deallocates a region of memory previously allocated by MALLOC(). The argument given to FREE() must be a pointer previously returned by MALLOC(), but not already given to FREE(). The memory is returned to the memory manager, making it unavailable to the programmer.

Example: Deallocate via FREE:

	POINTER ( P1, X ), ( P2, Y ), ( P3, Z ) 
	P1 = MALLOC ( 10000 ) 
	CALL FREE ( P1 ) 

In the above example, MALLOC() allocates 10,000 bytes of memory, which are associated with pointer P1. FREE() later returns those same 10,000 bytes to the memory manager.

Special Considerations

Here are some special considerations when working with pointers and memory allocation with malloc(), loc(), and free():