Skip to content
Fortran

Pointers and Allocatables

Dynamic memory allocation in Fortran.

By EZ4Code Team
allocatablepointermemory

Code

program dynamic_memory
  implicit none

  ! Allocatable (preferred — auto-freed on scope exit)
  real, allocatable :: arr(:)
  integer :: stat

  allocate(arr(1000), stat=stat)
  if (stat /= 0) stop 'Allocation failed'
  arr = 42.0
  print *, size(arr), arr(1)
  deallocate(arr)  ! optional — auto on scope exit

  ! Allocatable in derived type
  type :: matrix
    real, allocatable :: data(:,:)
  end type
  type(matrix) :: m
  allocate(m%data(10, 10))
  m%data = 0.0

  ! Pointer (manual lifetime, can be reassigned)
  real, target :: x = 5.0
  real, pointer :: p
  p => x
  print *, p  ! 5.0
  p = 10.0    ! modifies x
  print *, x  ! 10.0

  ! Automatic reallocation on assignment
  arr = [1.0, 2.0, 3.0]  ! reallocates to size 3
end program

Explanation

allocatable is preferred over pointer for dynamic arrays — automatic deallocation on scope exit prevents leaks. Use stat= to check allocation success (out-of-memory). target/pointer is for aliasing existing variables. Modern Fortran (2003+) auto-reallocates on assignment, simplifying code. Prefer allocatable for arrays; reserve pointer for graphs/trees.

More Fortran Snippets