Dynamic storage allocation

Allocating storage for arrays

If the required size of an array is not known at compile time, it can be declared with the ALLOCATABLE attribute. For example:

REAL,ALLOCATABLE::ar(:,:)

declares ar to be a REAL, two-dimensional array of undefined shape.

At run time when the required shape becomes known, storage can be allocated dynamically using ALLOCATE. For example:

INTEGER n,ErrorState
! Code to determine the value of n
ALLOCATE(ar(n,n),STAT=ErrorState)
IF(ErrorState>0) STOP "Failed dynamic allocation"

The STAT argument is optional.

Allocated memory is obtained from an area of memory called the heap. It is automatically returned when the program terminates or (if the array is local to a procedure) when a RETURN is executed. Otherwise, memory can be explicitly returned by using DEALLOCATE. For example:

DEALLOCATE(ar)

The ALLOCATED intrinsic function can be used to determine if an array is currently allocated.

 

Allocating storage for structures

By using the ALLOCATE statement, it is also possible to allocate memory for a structure referenced only by a pointer. The following example, though trivial, illustrates the idea.

REAL,POINTER::x
ALLOCATE(x)
x=1.0
DEALLOCATE(x)

DEALLOCATE returns the storage and nullifies the pointer.

In the case of arrays, the attributes ALLOCATABLE and POINTER are synonymous.

 

The NULLIFY statement

Given a pointer ptr, the statement

NULLIFY(ptr)

sets ptr to the null state. After ptr has been nullified, ASSOCIATED(ptr) will return FALSE.

 

 

Basket
Empty
 
Copyright © 1999-2024 Silverfrost Limited