Heap storage should be reclaimed using the DEALLOCATE statement:
IF (ALLOCATED(ages)) DEALLOCATE(ages,STAT=ierr)
As a matter of course, the LOGICAL valued intrinsic inquiry function, ALLOCATED, should be used to check on the status of the array before attempting to DEALLOCATE because it is an error to attempt to deallocate an array that has not previously been allocated space or one which does not have the ALLOCATE attribute. Again one should only supply one array per DEALLOCATE statement and the optional STAT= field should always be used. ierr holds a value that reports on the success / failure of the DEALLOCATE request in an analogous way to the ALLOCATE statement.
Memory leakage will occur
if a procedure containing an allocatable array (which does not possess
the SAVE attribute) is exited without the array being
DEALLOCATE d
.
The storage associated with this array becomes inaccessible for the
whole of the life of the program.
Consider the following sorting program which can handle any number of items,
PROGRAM sort_any_number
!---------------------------------------------------------!
! Read numbers into an array, sort into ascending order !
! and display the sorted list !
!---------------------------------------------------------!
INTEGER, DIMENSION(:), ALLOCATABLE :: nums
INTEGER :: temp, I, K, n_to_sort, ierr
PRINT*, 'How many numbers to sort'
READ*, n_to_sort
ALLOCATE( nums(1:n_to_sort), STAT=ierr)
IF (ierr .NE. 0) THEN
PRINT*, "nums: Allocation request denied"
STOP ! halts execution
END IF
PRINT*, 'Type in ',n_to_sort, 'values one line at a time'
DO I=1,n_to_sort
READ*, nums(I)
END DO
DO I = 1, n_to_sort-1
DO K = I+1, n_to_sort
IF(nums(I) > nums(K)) THEN
temp = nums(K) ! Store in temporary location
nums(K) = nums(I) ! Swap the contents over
nums(I) = temp
END IF
END DO
END DO
DO I = 1, n_to_sort
PRINT*, 'Rank ',I,' value is ',nums(I)
END DO
IF (ALLOCATED(nums)) DEALLOCATE(nums, STAT=ierr)
IF (ierr .NE. 0) THEN
PRINT*, "nums: Deallocation request denied"
END IF
END PROGRAM sort_any_number
Return to corresponding overview page