Code
fortran
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